To flatten a list of lists means to take the items out of the inner lists and put them all in one list, in the same order.
The program
nested = [[1, 2], [3, 4, 5], [], [6]] flat = [] for inner in nested: for item in inner: flat.append(item) print(flat)
[1, 2, 3, 4, 5, 6]
How it works
- The outer loop takes one inner list at a time. The inner loop takes each item from that list and appends it to
flat. - The empty list
[]adds nothing, so it needs no special case.
The same two loops fit in one list comprehension. The for parts are in the same order as in the loop version:
nested = [[1, 2], [3, 4, 5], [], [6]] flat = [item for inner in nested for item in inner] print(flat)
[1, 2, 3, 4, 5, 6]
Lists nested to any depth
The versions above go only one level deep. When lists can hold lists that hold more lists, a recursive function handles every level: when an item is itself a list, the function calls itself on that item.
def flatten(items): result = [] for item in items: if isinstance(item, list): result.extend(flatten(item)) else: result.append(item) return result print(flatten([1, [2, [3, [4]], 5], [[6]]]))
[1, 2, 3, 4, 5, 6]
result.extend(...) adds every item of a list to result, while append would add the list as one item.