ProgrammingHardAccenture pattern

What is printed?

What is printed?
def flatten(lst):
    for item in lst:
        if isinstance(item, list):
            yield from flatten(item)
        else:
            yield item
print(list(flatten([1, [2, [3, 4], 5], 6])))
  1. A. [1, 2, 3, 4, 5, 6]
  2. B. [1, [2, [3, 4], 5], 6]
  3. C. [1, 2, [3, 4], 5, 6]
  4. D. [1, 2, 3, 4, 5]

Correct answer: A. [1, 2, 3, 4, 5, 6]

flatten recurses with yield from into every nested list, so all scalars at any depth are yielded in order: 1, 2, 3, 4, 5, 6.

More Python Programming questions

Exams that ask this topic