Weird behaviour

That would break a lot of existing codes that rely on the current behavior.

And there’s already a widely accepted workaround of storing the iterating value as a default value to a parameter of the lambda function:

>>> l = [ (lambda i=i: i) for i in (1, 2, 3) ]
>>> [ f() for f in l ]
[1, 2, 3]
3 Likes

Let me think about this, not conviced yet, but thanks!
“widely accepted” ? Any reference ? Just asking.

I buy your fix Ben !

But I still think that the original (without i=i) should behave the same.

It makes perfect sense (event if weird) thanks Ben. To be added in the doc ?
“Comprehension leakages: how to avoid them”.
Going back to LISP :slight_smile:

To put this into perspective: I’m teaching Python. I insist on the fact that there are no scopes in Python, but namespaces and LEGB. It appears as it is equivalent to lexical scoping, but it is NOT.
I ended up with bugs when coding while it was as if Python had lexical scope.
I ended up with bugs.
I missed block-level scope (there is no spoon, right ?)
My 2ç

Python is NOT a lexical language. Face it or leave it. Ok :slight_smile:

No cigar: my lambdas are not awaiting arguments, your are;

You can search for “python lambda list comprehension same value” to find tons of Q&As on this topic, all of which point to this very solution.

Here’s one of the them:

It already is:

3 Likes

Lexical scoping just means that a variable’s scope is statically bound by where it is defined. It does not mean that a snapshot of a variable’s value has to be taken when the variable is defined. So Python does use lexical scoping, with values resolved by the LEGB rule.

2 Likes