Exercise 5: Flatten a Nested List Without Recursion — Possible Solution ==================================================================== nested = [1, [2, [3, 4]], 5, [[6], 7]] flat = [] stack = [nested] while stack: item = stack.pop() if isinstance(item, list): stack.extend(reversed(item)) else: flat.append(item) print(flat) Example run: [1, 2, 3, 4, 5, 6, 7] WHY THIS WORKS AS AN ANSWER ------------------------------ A stack gives out the item that went in last, so to read a list from left to right its items are pushed in reverse: stack.extend(reversed(item)). Each pass takes one item. If it is a list, its contents go back on the stack for later; if it is a plain value, it is the next one for the result. The number of passes is not known in advance, and it grows while the loop is running whenever a list is found, which is exactly the case for while and not for a for loop over a fixed list. The loop ends when the stack is empty, because an empty list is false.