ProgrammingHardTCS NQT · Accenture

What is printed?

What is printed?
print([x for x in [1, 2, 3] for _ in range(x)])
  1. A. [1, 2, 3]
  2. B. [1, 2, 2, 3, 3, 3]
  3. C. [1, 1, 2, 3]
  4. D. [1, 2, 2, 3, 3]

Correct answer: B. [1, 2, 2, 3, 3, 3]

The outer loop picks each x and the inner loop repeats it x times, so 1 appears once, 2 twice and 3 three times.

More Python Programming questions

Exams that ask this topic