TGViewer
Python Learning Python Learning @python_bds Β· 5.74K subscribers
Post #1313 57
πŸ› This Python Bug Looks Random, But It Isn't

Look at this:
functions = []

for i in range(3):
functions.append(lambda: i)

for f in functions:
print(f())


What would you expect?
0
1
2

Actual output:
2
2
2


Why? The lambdas don't store the current value of i. They remember the variable i.
By the time the functions are called, the loop has finished and i is 2.

This is called late binding.
If you actually want each function to capture the current value:
functions = []

for i in range(3):
functions.append(lambda i=i: i)

Now:
0
1
2


This becomes particularly important when creating callbacks inside loops, especially in GUI code, asynchronous code, and event-driven applications.

The bug isn't in lambda. It's in understanding when the variable is looked up.
  • ❀ 1
More from @python_bds
  1. Oct 6, 2026🐍 Python Performance Optimization Python Performance Optimization: Make Your Code Faster…
  2. Oct 4, 2026Python Set Methods ✍️
  3. Oct 3, 2026Post #1310
  4. Oct 1, 2026🐍 Python Beginner Notes
  5. Sep 30, 2026🧠 return vs print() in Python These are not interchangeable. def add(a, b): print(a + b)…
  6. Sep 28, 2026PYTHON SKILL ROADMAP β”‚ β”œβ”€β”€ πŸ“ Python Basics β”‚ β”œβ”€β”€ πŸ“ Variables & Data Types β”‚ β”œβ”€β”€ πŸ“ Input…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook β†’Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 β†’