Flattening Lists

Learn how to shift from a fully recursive solution to a less recursive solution.

Fully recursive solution

Consider this list:

[1, [2, 3], 4, [[5, 6], 7]] 

This list contains a mixture of integers and lists. These lists can also contain a mixture of integers and lists, and, in fact, the whole thing can be nested to any depth. You want to flatten this into a single list containing all the integers in the order they occur in the original unflattened list, as shown here:

[1, 2, 3, 4, 5, 6, 7] 

This is quite interesting because it is hard to come up with a solution that doesn’t involve recursion. But there are different degrees to which you can use recursion ...