How to Flatten a List of Lists in Python?

Recently, in a Python webinar, someone asked me a question about flattening a list. After researching and testing various methods, I found five effective methods to accomplish this task. In this article, I will explain how to flatten a list of lists in Python with examples and screenshots of executed example code.

Flatten a List of Lists in Python

Imagine you have a list of lists representing population data for various US cities:

population_data = [
    ['New York', 'NY', [8336817, 8804190, 8175133]],
    ['Los Angeles', 'CA', [3898747, 3898747, 3898747]],
    ['Chicago', 'IL', [2746388, 2746388]],
    ['Houston', 'TX', [2320268, 2320268, 2320268]],
    ['Phoenix', 'AZ', [1680992, 1680992, 1680992, 1680992]]
]

The goal is to flatten this list of lists into a single list containing all the elements:

['New York', 'NY', 8336817, 8804190, 8175133, 'Los Angeles', 'CA', 3898747, 3898747, 3898747, 'Chicago', 'IL', 2746388, 2746388, 'Houston', 'TX', 2320268, 2320268, 2320268, 'Phoenix', 'AZ', 1680992, 1680992, 1680992, 1680992]

Read How to Sort a List of Tuples in Python?

Method 1: Use Nested For Loops

One simple approach to flatten a list of lists is to use nested for loops in Python. This method involves iterating over each sublist and appending its elements to a new list. Here’s an example:

def flatten_list_nested_loops(nested_list):
    flat_list = []
    for sublist in nested_list:
        for item in sublist:
            if isinstance(item, list):
                for subitem in item:
                    flat_list.append(subitem)
            else:
                flat_list.append(item)
    return flat_list

flattened_data = flatten_list_nested_loops(population_data)
print(flattened_data)

Output:

['New York', 'NY', 8336817, 8804190, 8175133, 'Los Angeles', 'CA', 3898747, 3898747, 3898747, 'Chicago', 'IL', 2746388, 2746388, 'Houston', 'TX', 2320268, 2320268, 2320268, 'Phoenix', 'AZ', 1680992, 1680992, 1680992, 1680992]

You can see the output in the screenshot below.

Flatten a List of Lists in Python

This approach is easy to understand but can become cumbersome and inefficient for deeply nested lists.

Check out How to Filter Lists in Python?

Method 2: Use Recursion

Another way to flatten a list of lists is by using recursion in Python. Recursion is a powerful technique where a function calls itself to solve a problem by breaking it down into smaller subproblems. Here’s an example of a recursive function to flatten a list:

def flatten_list_recursion(nested_list):
    flat_list = []
    for item in nested_list:
        if isinstance(item, list):
            flat_list.extend(flatten_list_recursion(item))
        else:
            flat_list.append(item)
    return flat_list

flattened_data = flatten_list_recursion(population_data)
print(flattened_data)

Output:

['New York', 'NY', 8336817, 8804190, 8175133, 'Los Angeles', 'CA', 3898747, 3898747, 3898747, 'Chicago', 'IL', 2746388, 2746388, 'Houston', 'TX', 2320268, 2320268, 2320268, 'Phoenix', 'AZ', 1680992, 1680992, 1680992, 1680992]

You can see the output in the screenshot below.

How to Flatten a List of Lists in Python

Recursion provides a concise and elegant solution, especially for irregularly nested lists. However, it can be less efficient for large lists due to the overhead of function calls.

Read How to Sort a List of Objects by Attribute in Python?

Method 3: Use List Comprehension

Python list comprehension is a compact and efficient way to create new lists based on existing lists. It can also be used to flatten a list of lists in a single line of code. Here’s an example:

def flatten_list_comprehension(nested_list):
    return [item for sublist in nested_list for item in (flatten_list_comprehension(sublist) if isinstance(sublist, list) else [sublist])]

flattened_data = flatten_list_comprehension(population_data)
print(flattened_data)

Output:

['New York', 'NY', 8336817, 8804190, 8175133, 'Los Angeles', 'CA', 3898747, 3898747, 3898747, 'Chicago', 'IL', 2746388, 2746388, 'Houston', 'TX', 2320268, 2320268, 2320268, 'Phoenix', 'AZ', 1680992, 1680992, 1680992, 1680992]

You can see the output in the screenshot below.

Flatten a List of Lists in Python list comprehension

List comprehension offers a concise and readable solution, but it can be less intuitive for complex nested structures.

Check out How to Print a List Without Brackets in Python?

Method 4: Use itertools.chain

The itertools module in Python provides a chain function that can be used to flatten a list of lists. It works by iterating over the elements of multiple iterables and returning them as a single iterable. Here’s an example:

from itertools import chain

def flatten_list_itertools(nested_list):
    return list(chain.from_iterable(nested_list))

flattened_data = flatten_list_itertools(population_data)
print(flattened_data)

Output:

['New York', 'NY', [8336817, 8804190, 8175133], 'Los Angeles', 'CA', [3898747, 3898747, 3898747], 'Chicago', 'IL', [2746388, 2746388], 'Houston', 'TX', [2320268, 2320268, 2320268], 'Phoenix', 'AZ', [1680992, 1680992, 1680992, 1680992]]

Note that itertools.chain flattens the list by one level. If you have a deeply nested list, you may need to apply chain recursively.

Read How to Generate a List of Random Numbers in Python?

Method 5: Use functools.reduce

The functools module in Python provides a reduce function that can be used in combination with the operator.add function to flatten a list of lists. The reduce function applies a function of two arguments cumulatively to the items of a sequence, reducing the sequence to a single value. Here’s an example:

from functools import reduce
from operator import add

def flatten_list_reduce(nested_list):
    return reduce(add, nested_list)

flattened_data = flatten_list_reduce(population_data)
print(flattened_data)

Output:

['New York', 'NY', 8336817, 8804190, 8175133, 'Los Angeles', 'CA', 3898747, 3898747, 3898747, 'Chicago', 'IL', 2746388, 2746388, 'Houston', 'TX', 2320268, 2320268, 2320268, 'Phoenix', 'AZ', 1680992, 1680992, 1680992, 1680992]

This method is concise and efficient but may be less readable compared to other approaches.

Check out How to Slice Lists in Python?

Conclusion

In this tutorial, I helped you to learn how to flatten a list of lists in Python. I explained five important methods to accomplish this task, such as using nested for loop, using recursion, using list comprehension, using itertools.chain, and using functools.reduce with examples.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.