Editor

Tricky Python: What Does This Print

What does this print? · Advanced · about 10 min

Read each short program and type exactly what it prints, with each printed line on its own line.

Example

x = [0] * 3
print(x)

prints

[0, 0, 0]
  1. Program 1

    def add(item, bag=[]):
        bag.append(item)
        return bag
    add(1)
    print(add(2))
  2. Program 2

    funcs = []
    for i in range(3):
        funcs.append(lambda: i)
    print([f() for f in funcs])
  3. Program 3

    funcs = [lambda i=i: i * 10 for i in range(3)]
    print([f() for f in funcs])
  4. Program 4

    grid = [[0] * 2] * 3
    grid[0][0] = 1
    print(grid)
  5. Program 5

    def loud(x):
        print("checked", x)
        return x
    print(loud(0) and loud(1))
  6. Program 6

    print(-9 // 4, int(-9 / 4), -9 % 4)
  7. Program 7

    s = "hi"
    t = s
    s += "!"
    x = [1]
    y = x
    x += [2]
    print(s, t)
    print(x, y)
  8. Program 8

    nums = [1, 2, 2, 3]
    for n in nums:
        if n == 2:
            nums.remove(n)
    print(nums)