Search code examples
pythonfor-looplist-comprehension

Why does the list comprehension give off a different result than the for loop in this case (python)?


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.


Solution

  • 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