Member-only story
I Built Five Functions in a Loop. They All Did the Same Thing.
Why every function you create inside a for loop quietly captures the last value, and the one-word fix the Python docs give you
I needed five small functions, each squaring a different number.
You can read this article for free via this link ( my newsletter ): Click Here 👈
A loop felt like the obvious way to build them.
squares = []
for x in range(5):
squares.append(lambda: x ** 2)Five lambdas, one per value of x. I expected squares[0]() to give 0, squares[2]() to give 4, squares[4]() to give 16.
Here is what actually happened.
squares[2]() # 16
squares[4]() # 16
squares[0]() # 16Every single one returned 16.
Not the value from its own turn in the loop. The last value, 4 ** 2, for all of them. I had built five different functions and somehow gotten five copies of the same one.
I stared at this for a while. The loop clearly ran five times with five different values of x. The lambdas were clearly created at five different moments. So why did they all agree on the final answer?









