Search⌘ K
AI Features

Puzzle 11: Explanation

Explore how variable binding works in Python closures, especially within lambda functions. Understand why lambdas capture the same variable and learn two practical ways to fix related bugs, enhancing your problem-solving and coding skills.

We'll cover the following...

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] ...