TGViewer
Python Learning Python Learning @python_bds · 5.75K subscribers
Post #954 1.01K
Wait, why did all functions return 2?

The lambdas don’t capture the value of i at each loop iteration, they capture the variable itself. By the time you call the functions, the loop has finished, and i is left at its final value, 2.

This is called late binding and can cause unexpected behavior when creating closures inside loops.

So as a quick tip, Bind the current value at definition time using a default argument(like shown in the second image) Then each lambda remembers its own i value independently.
  • ❤ 2
More from @python_bds
  1. Oct 11, 2026📘 The Big Book of Small Python Projects ✍️ Author: Al Sweigart 🔗 Read Online #Python #Pr…
  2. Oct 10, 2026document post
  3. Oct 10, 2026This Book Explains more than 400 Concepts with codes.
  4. Oct 8, 2026🐛 This Python Bug Looks Random, But It Isn't Look at this: functions = [] for i in range(…
  5. Oct 6, 2026🐍 Python Performance Optimization Python Performance Optimization: Make Your Code Faster…
  6. Oct 4, 2026Python Set Methods ✍️
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 →