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!
Since a for loop is a statement (as is print , in Python 2. x), you cannot include it in a lambda expression.
We first iterate over the list using lambda and then find the square of each number. Here map function is used to iterate over list 1. And it passes each number in a single iterate. We then save it to a list using the list function.
The answer is it depends. I have seen cases where using a lambda was slower and where it was faster. I have also seen that with newer updates you get more optimal code.
Actually, list comprehension is much clearer and faster than filter+lambda, but you can use whichever you find easier. The first thing is the function call overhead: as soon as you use a Python function (whether created by def or lambda) it is likely that the filter will be slower than the list comprehension.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With