20+ examples for flattening lists in Python. Flattening lists means converting a multidimensional or nested list into a one-dimensional list. For example, the process of converting this [[1,2], [3,4]] list to [1,2,3,4] is called flattening. The process of flattening is very easy as we’ll see. You will learn how to flatten different shapes of lists with different techniques. So, let’s jump in. Let’s start with a simple example of converting [[0,1], [2,3]] into [0,1,2,3]. This type of flattening is called shallow flattening as it will only flatten lists of one level depth.
A list of lists
Using list comprehension
flatten_list = [item for subl in l for item in subl]
Let’s break this line of code.
The first loop is “for subl in l” and the second nested loop is “ for item in subl ”.
But our goal is to convert [ [ 0, 1 ], [ [ 2 ] ], [ 3, 4 ] ] this list to this [ 0, 1, 2, 3, 4 ] list. This problem can be solved with deep flattening. In deep flattening, the process undergoes multiple levels of depths to create a flattened list.
Check whether the list length is equal to 1. If true, then check whether the type of the first index of the list is a “list”.if true, then call the function that flattens the list else, store the number in the result.
Flatten without recursion
Flatten nested lists
Also, you can use the recursive function as we did above.
A list of tuples
Flatten 2d array
A list of NumPy arrays
There are three built-in functions defined in NumPy library that can convert the NumPy array into flattened lists.
The difference between these three functions is speed. The flatten function returns a copy every time it flattens the array. So, if you have a large data set, don’t use the flatten function; it’s the slower one.
Flatten JSON objects
For flattening JSON objects, there is a built-in function in the flatten_json library named flatten().
You first need to install it using pip:
pip install flatten_json
Then you can use this function in our code:
Flatten a list of objects
You can flatten a list of objects using a built-in function available in the itertools library with function name itertools.chain.from_iterable() Let’s see how to use this function:
The same operation can be achieved using list comprehension too:
Flatten a list of DataFrames
For flattening a list of DataFrames, the pandas library has a built-in function for flattening called df.concat() Let’s take a look at code:
Flatten & remove duplicates
First, we will flatten our list, then we will remove the duplicates.
For flattening the list, we will use our own flatten_without_rec() function, and then we will remove the duplicates.
Flatten a dictionary into a list
You can flatten a dictionary to a list using a simple for loop:
The reduce() function is defined in the functools library. You first need to import reduce from the functools.
We flattened lists with different shapes & types in different ways. I hope you find the tutorial useful. Keep coming back.