Predict the Output: Late Binding
Intermediate · Predict the output · from 15 Python Pitfalls That Trip Up Even Experienced Developers
From the lesson: 15 Python Pitfalls That Trip Up Even Experienced Developers
Python is famous for being readable and beginner-friendly. But lurking beneath that clean syntax are several traps that catch even experienced developers. These aren't bugs in Python - they're features that behave differently than you'd expect.
Read the lessonWhat does this code print? Think carefully about when the lambda reads the value of i.
functions = []
for i in range(3):
functions.append(lambda i=i: i * 10)
results = [f() for f in functions]
print(results)functions = []
for i in range(3):
functions.append(lambda i=i: i * 10)
results = [f() for f in functions]
print(results)
More Common Pitfalls exercises
- Fix the Mutable DefaultIntermediate
- Safe List FilteringIntermediate
- Fix the Bug: Shallow Copy SurpriseIntermediate
- Predict the Output: Variable ScopeIntermediate
- Safe Exception HandlingIntermediate
- Build a Safe Defaults FunctionIntermediate
All Python exercises · 50 practice problems · Advanced Python quiz