CS FundamentalsVery hardProduct-company placement · Python interview

Python generators implement the Iterator pattern lazily. What does this code print (lines joined by ' / ')?

Python generators implement the Iterator pattern lazily. What does this code print (lines joined by ' / ')?
def countdown(n):
    print("start")
    while n > 0:
        yield n
        n -= 1
    print("end")
g = countdown(3)
print("made")
print(next(g), next(g))
print(list(g))
  1. A. start / made / 3 2 / [1] / end
  2. B. made / start / 3 2 / end / [1]
  3. C. made / start / 3 2 / [1] / end
  4. D. start / made / 3 2 / end / [1]

Correct answer: B. made / start / 3 2 / end / [1]

Calling countdown(3) runs no code, so 'made' comes first; the first next() prints 'start' and yields 3, then 2. list(g) yields 1, prints 'end' when the loop finishes, and only then is [1] printed.

More Software Engineering, Git and Cloud Basics questions

Exams that ask this topic