MiddleCodeOccasionalNot answered yet
Flatten an arbitrarily nested list
Yield every leaf value from a list nested to any depth, left to right.
Requirements:
- Handle arbitrary nesting depth (lists inside lists inside lists...).
- Non-list items are leaves and are yielded as-is.
def flatten(nested):
# your code here
print(list(flatten([1, [2, [3, 4], 5], 6]))) # [1, 2, 3, 4, 5, 6]
Write the implementation.
Recurse with a generator: for each item, if it is a list, yield from flatten(item); otherwise yield item. yield from delegates to the sub-generator, flattening any depth lazily. Materialize the result with list(flatten(...)) when you need a concrete list.
- ✗Using a flat comprehension that only un-nests one level
- ✗Believing
sum(nested, [])recurses into deeper nesting - ✗Assuming lists have a built-in
flattenmethod
- →What does
yield fromdo that a plainfor ... yieldloop would also achieve? - →How would you extend this to flatten tuples and other iterables, not just lists?
Contents
Task
Implement flatten: lazily yield every leaf value from a list nested to any depth.
Solution
def flatten(nested):
for item in nested:
if isinstance(item, list):
yield from flatten(item) # recursive generator
else:
yield item
print(list(flatten([1, [2, [3, 4], 5], 6]))) # [1, 2, 3, 4, 5, 6]
Key points
yield fromdelegates to the sub-generator, passing its values outward — flattens any depth.- The generator is lazy: values stream on demand, with no intermediate lists built.
- The
isinstance(item, list)check separates branches from leaves.
Contents