+ 2

What happens with for-loops inside lambda functions?

Could you please explain the behaviour of for-loops inside lambda functions? See some sample code below: https://code.sololearn.com/cyR0wjAMWP7b/?ref=app

22nd Feb 2020, 10:12 AM
Lukas
8 Antworten
+ 2
HonFu we had it a few weeks ago... The list comprehension generates a closure and i is the same for all functions. If not wanted.. use () instead of []... tuple comprehension
22nd Feb 2020, 10:55 AM
Oma Falk
Oma Falk - avatar
+ 2
Ha, Oma, you're right! It took me a moment to find, but here's that discussion: https://www.sololearn.com/Discuss/2150955/?ref=app Lukas Wiedemann, do you find comprehensions in general ugly? I think they belong to the most convenient things you can do in Python, although it can be done too much.
22nd Feb 2020, 11:37 AM
HonFu
HonFu - avatar
+ 2
I do like list comprehensions but it was more about the fact that the for loop had no meaning at all in my code sample.. only the last value within the range(3) was assigned to i. The reason for that is still not clear to me. I might have to look at the bytecode ;) Also, thanks guys for all the quick answers. I like Oma Falk 's following code example showing different behaviour for tuple comprehensions: https://code.sololearn.com/cNU52yK69BSj/?ref=app
22nd Feb 2020, 12:18 PM
Lukas
+ 1
Oh yeah, we might also link that one: https://www.sololearn.com/Discuss/2049859/?ref=app
22nd Feb 2020, 12:36 PM
HonFu
HonFu - avatar
+ 1
Thanks HonFu
22nd Feb 2020, 12:40 PM
Lukas
0
This is not about the loop. This is abuout the fact that you multiply i with the same value every time. In your example the result will always be 8 because last value in range(3) is 2 and a=4 and this boils up to result 8
22nd Feb 2020, 10:31 AM
Gabriel Ilie
Gabriel Ilie - avatar
0
Lukas Wiedemann Closures is an advanced topic. Very mighty but one can live without.
22nd Feb 2020, 12:22 PM
Oma Falk
Oma Falk - avatar
0
I'm sure a python ide can help you to inspect variables.
24th Feb 2020, 9:53 AM
Logomonic Learning
Logomonic Learning - avatar