Replace the numbers below with anything you want.
lst = [
[[1, 2, 3], [4, 5]],
[[1, 2]],
[1, 2],
[[]],
[[1, 2, 3], [4, 5], [6, 7, 8]],
[[[1, 2, 3], [4, 5]], [[6, 7, 8]]],
]
Flatten with recursion (a function calling itself 'recursively')
def flatten(a_list, flat_list=None):
"""Change the isinstance as appropriate.
: Flatten an object using recursion
: see: itertools.chain() for an alternate method of flattening.
"""
if flat_list is None:
flat_list = []
for item in a_list:
if isinstance(item, list):
flatten(item, flat_list)
else:
flat_list.append(item)
return flat_list
Simple flattening
flatten(lst)
[1, 2, 3, 4, 5, 1, 2, 1, 2, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8]
Who says you can't start out with initial values.
flatten(lst, ['a', 'b']))
['a', 'b', 1, 2, 3, 4, 5, 1, 2, 1, 2, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8]