Select Page

How to Flatten a List of Lists in Python

by | Programming, Python, Tips

A nested or two-dimensional list is a list of lists, where each item in the nested list object is a list.

Flattening a list of lists involves extracting the elements of each sublist and putting them into a one-dimensional list.

We can use nested for loops, list comprehension, built-in functions and importing Python libraries to flatten a list of lists.

This tutorial will go through the various ways to make a flattened list from a list of lists in Python.


Using List Comprehension

List comprehension offers a shorter syntax to create a new list from the values of an existing list. The syntax for list comprehension is:

newlist = [expression for item in iterable if condition == True

The list comprehension returns a new list and leaves the old list unchanged.

Let’s look at an example of flattening a list of lists with the list comprehension:

# Define list

lst = [[2, 4, 6], [8, 10], [12, 14, 16, 18]]

# List comprehension 

flat_lst = [i for sublst in lst for i in sublst]

# Print 1D list 

print(flat_lst)

The list comprehension accesses each sublist in lst, then accesses each element of each sublist and stores them in flat_lst. Let’s run the code to see the result:

[2, 4, 6, 8, 10, 12, 14, 16, 18]

Using Nested For Loops

We can use a nested for loop, which is a for loop within a for loop to flatten a nested list. Let’s look at an example:

# Define list

lst = [[2, 4, 6], [8, 10], [12, 14, 16, 18]]

# Define new list to put elements

flat_lst = []

# First loop over sublists in list

for sublst in lst:

# Second loop in elements of each sub list

    for i in sublst:

# Append elements to empty list

        flat_lst.append(i)


# Print final 1D list

print(flat_lst)

In the above code, we create an empty list flat_lst. Then we access each element in each sublist using a nested loop and append the elements to the flat_lst. Let’s run the code to see the result:

[2, 4, 6, 8, 10, 12, 14, 16, 18]

The nested loop performs the same operation as the list comprehension. However, the list comprehension is succinct and Pythonic.

Using itertools.chain() method

The chain() method from the itertools library makes an iterator that returns elements from iterables that we pass to the method:

chain('ABC', 'DEF') ---≻ A B C D E F

Let’s look at an example of using the chain() method to flatten a list of lists:

import itertools

# Define list 

lst = [[2, 4, 6], [8, 10], [12, 14, 16, 18]]

# Use chain function to join all sublists to one list

flat_lst = list(itertools.chain(*lst))

# Print 1D list

print(flat_lst)

We use the unpacking operator * to unpack a list of lists into its sublists in the above code. We then pass the sublists to the chain() function, which will return all of the elements from every sublist. We then convert the output from the chain method to a list by using the list() method. Let’s run the code to see the result:

[2, 4, 6, 8, 10, 12, 14, 16, 18]

Using lambda and reduce()

In Python, an anonymous function is a function defined without a name. We define normal functions with the def keyword and anonymous functions with the lambda keyword. Therefore, an anonymous function is also called a lambda function. The syntax of a lambda function is:

lambda arguments: expression

Lambda functions can have any number of arguments but only have one expression. Let’s look at an example of using a lambda function with the reduce() method from the functools library.

from functools import reduce

# Define list

lst = [[2, 4, 6], [8, 10], [12, 14, 16, 18]]

# Use lambda function to sum inner sublists 

flat_lst = reduce(lambda x, y: x + y, lst)

# Print flattened list

print(flat_lst)

The reduce method applies a function of two arguments cumulatively to the items of an iterable from left to right to reduce the iterable to a single value.

In the above code, the function we pass to reduce is a lambda function that takes two arguments, x and y and returns the sum of x and y.

The x and y arguments are two sublists in the left to right order from the nested list. So the result of the reduce function using the lst object is:

(([2, 4, 6] + [8, 10]) + [12, 14, 16, 18])

Let’s run the code to get the result:

[2, 4, 6, 8, 10, 12, 14, 16, 18]

Using sum()

The sum() function takes two parameters: iterable, a list of lists, and start, an empty list. The empty list serves as the initial flat list to append elements from the inner sublists. The sum() function will add the sublists to produce a single one-dimensional list.

lst = [[2, 4, 6], [8, 10], [12, 14, 16, 18]]

# Use sum() function to add inner sublists

flat_lst = sum(lst, [])

# Print flattened list

print(flat_lst)

Let’s run the code to see the result:

[2, 4, 6, 8, 10, 12, 14, 16, 18]

Summary

Congratulations on reading to the end of this tutorial. You have gone through several ways to flatten a list of lists in Python. The simplest ways to flatten a list of lists are to use a list comprehension or the sum() method as they do not require importing any libraries.

To learn more about Python for data science and machine learning, go to the online courses page for Python.

Have fun and happy researching!