0

The language I am using is Python 3.10. I have been hunting a bug in my program for more than a week now, and it turns out that it was caused by my list comprehensions not giving the results I expected. I have written a simple example to showcase this behaviour:

alist = [1,2,3]

d = {}
for a in alist:
d[a] = lambda x: a + x

print([d[a](1) for a in alist])

for a in alist:
print(d[a](1))

This results to:

[4, 4, 4]
2
3
4

Does anyone know what is happening here? I guess that I will stop using dictionnaries of functions, but it still seems like it should work.

Valir23
  • 1
  • 2
  • for lambda, `a` is considered non-local variable, so its value is whatever it is in the enclosing scope - it doesn't "remember" the value from the time of definition. It's not the same `a` that is later used in list comprehension. You can force the `a` to be local variable of lambda by doing `lambda x, a=a: a + x` - aka making it an argument with default value of whatever `a` is at the time of lambda's definition – matszwecja Jan 11 '23 at 12:13
  • Please fix the indents in your code. – Сергей Кох Jan 11 '23 at 12:27

1 Answers1

0

I'll make matszwecja's comment the accepted answer, thanks!

for lambda, a is considered non-local variable, so its value is whatever it is in the enclosing scope. It's not the same a that is later used in list comprehension. You can force the a to be local variable by doing lambda x, a=a: a + x - aka making it an argument with default value of whatever a is at the time of lambda's definition

Valir23
  • 1
  • 2