Python loop for inside lambda

Python loop for inside lambda

Just in case, if someone is looking for a similar problem…

Most solutions given here are one line and are quite readable and simple. Just wanted to add one more that does not need the use of lambda(I am assuming that you are trying to use lambda just for the sake of making it a one line code).
Instead, you can use a simple list comprehension.

[print(i) for i in x]

BTW, the return values will be a list on None s.

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)

Python loop for inside lambda

To add on to chepners answer for Python 3.0 you can alternatively do:

x = lambda x: list(map(print, x))

Of course this is only if you have the means of using Python > 3 in the future… Looks a bit cleaner in my opinion, but it also has a weird return value, but youre probably discarding it anyway.

Ill just leave this here for reference.

Leave a Reply

Your email address will not be published. Required fields are marked *