Editor

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

flatten_nested_list.py
def flatten(items):
flat = []
for item in items:
if isinstance(item, list):
flat.extend(flatten(item)) # flatten the inner list first
else:
flat.append(item)
return flat
nested = [1, [2, 3], [4, [5, 6, [7]]], 8, []]
print("Nested list:", nested)
print("Flat list:", flatten(nested))
Output
Nested list: [1, [2, 3], [4, [5, 6, [7]]], 8, []]
Flat list: [1, 2, 3, 4, 5, 6, 7, 8]

How it works

  1. isinstance(item, list) checks whether an element is itself a list.
  2. A plain value is appended to flat straight away.
  3. An inner list is handed back to flatten(), which returns it as a flat list, and extend() adds all of its values.
  4. 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.
  5. The empty list at the end adds nothing, so it simply disappears.

Other ways to write it

One level deep with a list comprehension

One level deep with a list comprehension
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Read it like two loops: for each row, for each item in the row
flat = [item for row in matrix for item in row]
print("Flat list:", flat)
Output
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()

Using itertools.chain()
from itertools import chain
nested = [[1, 2], [3, 4, 5], [6]]
flat = list(chain.from_iterable(nested))
print("Flat list:", flat)
Output
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.

All Python programs · CBSE class 12 practical file · Python exercises