I was struggling with weird bug in my code. Following code is simple replication of that bug:
import random
array = []
for _ in range(0,5):
rand = random.randint(0,7)
print(f"adding lambda for rand = {rand}")
array.append(lambda : print(rand))
for e in array:
e()
My prediction was that e()
would print exactly the same numbers as the first loop but it didn't. After some time I figured it out that rand
is always the same place in memory and only the last change to its value will be used in lambda execution. The thing is as much as I understand how it works I don't understand why would someone possibly make programming language work this way. So here's my question: Why local variables in python point to the same place in memory even though it's not declared before the loop(scope)?