...

/

Puzzle 11: Explanation

Puzzle 11: Explanation

Let’s find out how closure works in Python and how to fix this bug.

Let’s try it!

Try executing the code below to verify the result:

Python 3.8
display = []
buttons = []
for n in range(10):
# A button is a function called when user clicks on it
buttons.append(lambda: display.append(n))
btn = buttons[3]
btn()
print(display)

Explanation

Most people expect the correct answer to be [3] ...