CodingNeed.

1 · Model, solve and test · 25 MIN

Consume a generator without losing order

Consume a generator without losing order

A generator yields values on demand and resumes from its last suspension point. This flatten generator visits pages and then each item within a page, preserving the original encounter order. The final list deliberately materializes the result because the exercise asks for a JSON array. Distinguish the generator’s small working state from that returned list: a streaming producer does not make a fully materialized result constant-space.

Use yield from for each inner iterable, then materialize only at the output boundary.

Read the example

def flatten(pages):
    for page in pages:
        yield from page
def solve(input):
    return list(flatten(input))
import json
print(json.dumps(solve(json.loads("[[1,2],[],[3]]")), separators=(",", ":")))
Check the expected output
[1,2,3]

Your challenge

Given a list of pages, each a list of numbers, return one flat list preserving page order and item order. Empty pages contribute no items.

Solution cost: O(p + n) for p pages and n items. time · O(n) returned list; constant extra generator state. space

Common trap

Calling list(generator) consumes the generator; a second iteration will not replay its values.

Next lesson: Merge sorted streams with a heap

Essential cookies keep your account signed in. Optional analytics is not configured on this site. Your choice does not affect access to lessons.

Read the Privacy Policy. You can change this choice in the footer.