Flatten Nested Lists
Write flatten(nested) that takes a list that may contain other lists or tuples, to any depth, and returns one flat list of the non-list items, in order.
flatten([1, [2, [3, [4]]], 5]) is [1, 2, 3, 4, 5]. Strings are items, not containers: flatten(["ab", ["cd"]]) is ["ab", "cd"].
Understand the problem
Find the base case and the recursive case.
For each element of the list, which two cases are there?
- It is a number or it is a string
- It is itself a list or tuple (go deeper), or it is a plain item (keep it)
- It is empty or not empty
That is the recursion. A plain item goes into the result. A list or tuple is flattened by calling the same function on it, and its result is added.
What goes wrong if you treat every iterable as a container, with try: iter(x)?
- Nothing
- A string is iterable and each character is again a string, so it recurses forever
- Numbers become strings
The string "a" is iterable, and its only item is "a", a one-character string, which is again iterable: infinite recursion. Test for list and tuple explicitly (isinstance(x, (list, tuple))).
Write the solution
Return the flat list.
def flatten(nested):
# Write your code here.
pass
Hint 1: a question to ask yourself
If you could flatten a smaller nested list for free, what would you do with the result for each element?
Hint 2: the shape of the answer
Make an empty result list. For each item: if it is a list or tuple, result.extend(flatten(item)); otherwise result.append(item).
Reflect
Solution: recursion
def flatten(nested):
result = []
for item in nested:
if isinstance(item, (list, tuple)):
result.extend(flatten(item))
else:
result.append(item)
return result
Another way: a stack, no recursion
def flatten(nested):
result = []
stack = [iter(nested)]
while stack:
for item in stack[-1]:
if isinstance(item, (list, tuple)):
stack.append(iter(item))
break
result.append(item)
else:
stack.pop()
return result
Another way: a generator
def flatten(nested):
def walk(items):
for item in items:
if isinstance(item, (list, tuple)):
yield from walk(item)
else:
yield item
return list(walk(nested))
What this tests: recursion with a base case, isinstance with a tuple of types, extend versus append, and the iterable-string trap.
Recursion in one sentence: solve the problem for the smaller pieces with the same function, then combine. The base case here is "an item that is not a list".
extend versus append: result.extend([1, 2]) adds the two items; result.append([1, 2]) adds one list.
Depth limit: Python stops at about 1000 nested calls (RecursionError). The stack version has no such limit, which is why interviewers sometimes ask for it.
Cost: O(total items).
What an interviewer might ask next: Make it lazy, so a huge structure is not built in memory. (A generator with yield from: the third solution walks lazily and only builds the list at the end.)
DEEP = [1]
for _ in range(149):
DEEP = [DEEP]
VISIBLE = 3
CASES = [
(([1, [2, [3, [4]]], 5],), [1, 2, 3, 4, 5], 'deep nesting'),
((['ab', ['cd']],), ['ab', 'cd'], 'strings are items'),
(([],), [], 'an empty list'),
(([[], [[]]],), [], 'only empty lists'),
(([1, (2, 3), [4, (5,)]],), [1, 2, 3, 4, 5], 'tuples are flattened too'),
(([1, 2, 3],), [1, 2, 3], 'already flat'),
((DEEP,), [1], 'nested 150 levels'),
(([['a'], 'b', [['c', ['d']]]],), ['a', 'b', 'c', 'd'], 'strings at several depths'),
(([None, [None]],), [None, None], 'None items'),
]