Practice · Code Reading · Python
What does this Python print?
The Python behaviour that trips people up in interviews and code reviews: default arguments, late binding, aliasing, generators, scope and more. Every program here has been run with Python 3, and the answers are what it really prints.
15 Python drills35 JavaScript drills →
1. A default list
def add(item, bucket=[]): bucket.append(item) return bucket print(add(1))print(add(2))2. Lambdas made in a loop
fns = [lambda: i for i in range(3)]print([f() for f in fns])3. b = a
a = [1, 2, 3]b = ab.append(4)print(a)4. A grid made with *
grid = [[0] * 2] * 2grid[0][0] = 1print(grid)5. Equal, but the same?
a = [1, 2]b = [1, 2]print(a == b, a is b)6. Changing a global
count = 0 def inc(): count += 1 inc()print(count)7. Brackets around one number
t = (5)u = (5,)print(type(t).__name__, type(u).__name__)8. Sum a generator twice
squares = (x * x for x in range(3))print(sum(squares))print(sum(squares))9. Which key comes first?
d = {}d["b"] = 1d["a"] = 2d["b"] = 3print(list(d))10. Dividing negatives
print(7 // 2, -7 // 2, 7 % -3)11. Chained comparisons
print(1 < 3 > 2, 1 < 3 < 2)12. for … else
for n in [3, 5, 7]: if n % 2 == 0: print("found", n) breakelse: print("no even number")13. A counter in a closure
def counter(): n = 0 def step(): nonlocal n n += 1 return n return step c = counter()c()c()print(c())14. Rounding halves
print(round(2.5), round(3.5), round(-0.5))15. return inside try
def f(): try: return "from try" finally: print("finally runs") print(f())