Python Code to Flatten a Nested List

A nested list is a list that has other lists inside it. Flattening means making one simple list with all the values. The list can be nested to any depth, so a recursive function is the best way.

Python function to flatten a list

def flatten(items):
    result = []
    for item in items:
        if isinstance(item, list):
            result.extend(flatten(item))
        else:
            result.append(item)
    return result

nested = [1, [2, 3], [4, [5, 6]], 7]
print(flatten(nested))

Output:

Tutorials Class - Output Window

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

How it works

  • The function goes through each item of the list.
  • If the item is also a list (isinstance(item, list)), the function calls itself for it and adds the flat result with extend().
  • Otherwise, the item is a plain value and is added with append().

For a list that is only one level deep, a list comprehension is enough:

matrix = [[1, 2], [3, 4], [5]]
flat = [x for row in matrix for x in row]
print(flat)

Output:

Tutorials Class - Output Window

[1, 2, 3, 4, 5]

Related: Python Lists and Python Functions (recursion).


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.