Python Program to Flatten a Nested List
Intermediate · Lists
A nested list is a list that contains other lists, such as [1, [2, 3], [4, [5]]]. Flattening it means pulling every value out into one plain list: [1, 2, 3, 4, 5]. This program uses a recursive function, so it works however deep the lists are nested.
Program
Nested list: [1, [2, 3], [4, [5, 6, [7]]], 8, []] Flat list: [1, 2, 3, 4, 5, 6, 7, 8]
How it works
isinstance(item, list)checks whether an element is itself a list.- A plain value is appended to
flatstraight away. - An inner list is handed back to
flatten(), which returns it as a flat list, andextend()adds all of its values. - Because the function calls itself for every inner list, a list nested three levels deep, like
[5, 6, [7]], is handled the same way as one level. - The empty list at the end adds nothing, so it simply disappears.
Other ways to write it
One level deep with a list comprehension
Flat list: [1, 2, 3, 4, 5, 6, 7, 8, 9]
For a list of lists, one level deep, a comprehension with two for parts is the usual one-liner. It does not reach lists nested any deeper.
Using itertools.chain()
Flat list: [1, 2, 3, 4, 5, 6]
chain.from_iterable() reads the inner lists one after another, which is fast and clear for one level of nesting.
Try it yourself
Add a string such as "hi" to the nested list and check that it stays whole in the flat list.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
- Find the Sum of a Nested List
- Split a List into Chunks
- Merge Two Lists
- Find the Sum of a List Using Recursion
- Find the Largest and Smallest Number in a List
- Swap Elements at Even and Odd Positions in a List
- Find the Second Largest Number in a List
- Remove Duplicates from a List
- a Menu-Driven List
- Find the Sum of Elements in a List
All Python programs · CBSE class 12 practical file · Python exercises