Editor

Comprehensions: What Does This Print

What does this print? · Intermediate · about 8 min

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

Example

print([n + 1 for n in [1, 2, 3]])

prints

[2, 3, 4]
  1. Program 1

    print([x for x in range(10) if x % 3 == 0])
  2. Program 2

    print([x if x > 2 else 0 for x in [1, 2, 3, 4]])
  3. Program 3

    print([(a, b) for a in range(3) for b in range(3) if a < b])
  4. Program 4

    words = ["sun", "moon", "sky"]
    print({w: len(w) for w in words})
  5. Program 5

    print(sorted({n % 3 for n in range(10)}))
  6. Program 6

    gen = (x * x for x in range(4))
    print(sum(gen), sum(gen))
  7. Program 7

    x = 10
    nums = [x for x in range(3)]
    print(x, nums)
  8. Program 8

    m = [[1, 2], [3, 4]]
    print([[row[i] for row in m] for i in range(2)])