ProgrammingHardTCS CodeVita · Infosys HackWithInfy

What is printed?

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

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

Each nested list is passed to a recursive generator with yield from, which passes every leaf value up. The depth here is only 4, so no recursion limit is reached.

More Python Programming questions

Exams that ask this topic