PyCodeItPython trace & interview prep
DashboardMastery MapSQL PracticeDailyInterviewBlogLeaderboardCommunity

Loading PyCodeIt workspace...

PyCodeIt

Free interactive learning platform for Python code tracing, SQL queries, and technical interviews. Built for bootcamp grads, computer science students, and engineers.

Python Practice

  • Learning Center
  • For loop tracing
  • List tracing
  • Dictionary tracing
  • Decorators practice
  • Python Tracing Guide
  • Python Output Questions

SQL Practice

  • SQL Fundamentals
  • Relational JOINs
  • Window Functions
  • CTEs & Set Operators
  • SQL JOINs Guide
  • Window Functions Guide

Legal

  • About
  • Contact
  • Privacy Policy
  • Terms of Service

© 2026 PyCodeIt 2026. All rights reserved.

Late-Binding in Closures: A Common Trap

Lambdas defined inside loops often capture the loop variable by reference. We walk through the trace and show a safe pattern to capture the current value.

funcs = [lambda: i for i in range(3)]
print([f() for f in funcs])  # prints [2,2,2]

Why it prints [2,2,2]

The lambda captures the name `i`, not its value at definition time. When the lambdas run, `i` has the final loop value (2), so each lambda returns 2.

Fix: capture by default parameter

funcs = [lambda i=i: i for i in range(3)]
print([f() for f in funcs])  # prints [0,1,2]
Companion video:
Python Late Binding Explained in 30 Seconds
Short explainer: shows the lambda late-binding trap and a simple fix.
Return to Practice