20 AnswersNew Answer
20 AnswersNew Answer
Kishalaya Saha yes... a list comprehension generates a closure but not a.... tuple comprehension... i. E generator.
Ha, nice, I knew I had explained it somewhere but didn't know when and where. You guys found it! :) Thx, Qasem!
HonFu but not the function makes the closure. Otherwise my linked prog couldn't work. It is the list comprehension
yessine HonFu ..... It is worth that. Real cool stuff.
Oma Falk, ah, yes, I think, there's not really a difference in what we're saying. In that other thread I just 'translated' the list comp to a regular nested function creating the same closure effect, in order to illustrate it.
HonFu if you await behavior in that prog, you are right https://code.sololearn.com/cNU52yK69BSj/?ref=app
actually the second version is a generator, not a tuple , am I not right ?
Yeah, a generator is only a 'construction plan', so that generator will generate each function object as needed and hand over the latest i. Interesting! If I apply that old pattern of explanation, it would look like this now: def cm(): def f(x): return x*i l =  for i in range(3): yield f
Katie Hattab you have a contribution to that topic ?
Yes, Qasem you found it, thank you
yessine you're absolutely right! It's a generator, not a tuple. And that explains it!
I try to explain easier: All lambdas in cm depend on one variable i. But one variable can only have one value - that is the last one assigned to it = 2. Closures are really a bit tricky
In cm the function objects are not really built in list comprehension but only their description. Although the defining function is gone, they remember life in their function and share the same last memory concerning i which is 2. So we have a closure.
cm2 is not a closure all lambda are independent of their birthplace and share no common value.
By the way...it is easy to curate since tuples don't create an own closure https://code.sololearn.com/cJiE17h7fR1v/?ref=app
Oma Falk, seems I have to catch up with what you wrote and think about it for a moment...
Oma Falk I think difference in your version might have something to do with tuples being immutable. If we replace it by a list, a set, or even a dictionary, it works (fails?) like before. P.S. I, too, attempted to explain this code nearly a year ago 😄 It's pretty similar to what you and HonFu said. https://www.sololearn.com/Discuss/1577036/list-lambda Edit: turns out it's not a tuple, but a generator, as pointed out later. And it makes a lot more sense.
Oma Falk I don't know what's a function description.. I guess I'll have to learn about it.
Learn Playing. Play Learning
SoloLearn Inc.4 Embarcadero Center, Suite 1455
Send us a message