Fernando Retimo Fernando Retimo - 3 months ago 14
Python Question

Python loop for inside lambda

In my code I need to simplify as much as possible my line of code.
EDIT: I think I'm not clear enough - 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)


I just do not know how to make it happen.
Thanks!

Answer

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")