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. 1. A default list

    bucket.py
    def add(item, bucket=[]):    bucket.append(item)    return bucket print(add(1))print(add(2))
    What does this print?
  2. 2. Lambdas made in a loop

    lambdas.py
    fns = [lambda: i for i in range(3)]print([f() for f in fns])
    What does this print?
  3. 3. b = a

    alias.py
    a = [1, 2, 3]b = ab.append(4)print(a)
    What does this print?
  4. 4. A grid made with *

    grid.py
    grid = [[0] * 2] * 2grid[0][0] = 1print(grid)
    What does this print?
  5. 5. Equal, but the same?

    same.py
    a = [1, 2]b = [1, 2]print(a == b, a is b)
    What does this print?
  6. 6. Changing a global

    count.py
    count = 0 def inc():    count += 1 inc()print(count)
    What happens?
  7. 7. Brackets around one number

    tuple.py
    t = (5)u = (5,)print(type(t).__name__, type(u).__name__)
    What does this print?
  8. 8. Sum a generator twice

    squares.py
    squares = (x * x for x in range(3))print(sum(squares))print(sum(squares))
    What does this print?
  9. 9. Which key comes first?

    keys.py
    d = {}d["b"] = 1d["a"] = 2d["b"] = 3print(list(d))
    What does this print?
  10. 10. Dividing negatives

    divide.py
    print(7 // 2, -7 // 2, 7 % -3)
    What does this print?
  11. 11. Chained comparisons

    compare.py
    print(1 < 3 > 2, 1 < 3 < 2)
    What does this print?
  12. 12. for … else

    search.py
    for n in [3, 5, 7]:    if n % 2 == 0:        print("found", n)        breakelse:    print("no even number")
    What does this print?
  13. 13. A counter in a closure

    counter.py
    def counter():    n = 0    def step():        nonlocal n        n += 1        return n    return step c = counter()c()c()print(c())
    What does this print?
  14. 14. Rounding halves

    round.py
    print(round(2.5), round(3.5), round(-0.5))
    What does this print?
  15. 15. return inside try

    finally.py
    def f():    try:        return "from try"    finally:        print("finally runs") print(f())
    What does this print?