flatten list of lists

How to Flatten List of Lists in Python

A list of lists (2D list) is when each element of a list is also a list. Sometimes you may need to convert a 2D list into a 1D list, also known as flattening a list of lists. There are plenty of ways to do this. In this article, we will look at different ways to flatten list of lists in Python.


How to Flatten List of Lists in Python

Here are the different ways to flatten list of lists in Python. Let us say you have the following 2D list, or list of lists in python.

list = [[ 2, 3, 4], [5, 6, 7], [8, 9]]


1. Using List Comprehension

Here is a simple way to flatten the above list

flat_list = [item for sublist in list for item in sublist]
flat_list
[2, 3, 4, 5, 6, 7, 8, 9]

The above list comprehension basically loops through the 2D list while building our 1D list.


2. Using sum

Here is another simple way to convert flatten a list by just adding an empty list to your 2D list. However, this is not as fast as other methods and can be used for medium-sized lists.

flat_list = sum(list,[])
flat_list
[2, 3, 4, 5, 6, 7, 8, 9]


3. Using itertools

itertools is a python library that allows you to work with iterable data structures like list. It provides plenty of useful functions, one of them being chain(). Here is an example to flatten list of lists using itertools. This is the fastest method as it treats the entire list of lists as a single sequence when iterates through the items sequentially.

import itertools 
list = [[2, 3, 4], [5, 6, 7], [8, 9, 10]] 
flat_list = list(itertools.chain(*list)) 
flat_list
[2, 3, 4, 5, 6, 7, 8, 9]


4. Using numpy

You may also use numpy library to convert 2D list to 1D list as shown below. It also provides many operators and functions to work with iterable data structures like lists. We will use concatenate and flat functions for our purpose.

import numpy
regular_list = [[2, 3, 4], [5, 6, 7], [8, 9]]
flat_list = list(numpy.concatenate(regular_list).flat)
flat_list
[2, 3, 4, 5, 6, 7, 8, 9]

However, the above approach is also slower than other approaches.

In this article, we have seen 4 different ways to flatten list of lists. There are many more ways to do this. Out of them using itertools & chain function gives you the fastest result.

Also read:

How to Find Element in List using Python
How to Parse CSV File in Shell
How to Find Symlinks to Folder/Directory in Linux
Shell Script to Count Number of Files in Directory
How to Enable & Disable Services in Linux

Leave a Reply

Your email address will not be published. Required fields are marked *