Search code examples
pythonfor-looplambda

loop for inside lambda


I need to simplify my code as much as possible: it needs to be one line of code. I need to put a for loop inside a lambda expression, something like that:

x = lambda x: (for i in x : print i)

Solution

  • Since a for loop is a statement (as is print, in Python 2.x), you cannot include it in a lambda expression. Instead, you need to use the write method on sys.stdout along with the join method.

    x = lambda x: sys.stdout.write("\n".join(x) + "\n")