20+ examples for flattening lists in Python

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

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.

Using list comprehension

List comprehension is a way to create lists in one line of code. Let’s see how we can use list comprehension for flattening the lists.

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 ”.

Deep flattening

When we will try to flatten a list of varying depth like this [ [ 0, 1 ], [ [ 2 ] ][ 3, 4 ] ] list with shallow flattening, the output will be as follows:

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.

There is a built-in function named deepflatten in the iteration_utilities library. You need to install this library using.

We have successfully achieved our target. Let’s take another example by changing the depth of the list.

Using recursion

To flatten a list recursively, we will call the function inside itself to run until the end:

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.

The function will be like this:

When we run this code against this [[0,1], [2], [3,4]] list, the results will be:

Flatten without recursion

To flatten a list without recursion, we will use a while loop until we pop all the elements from it. Take a look at the code, you will have a better understanding:

Flatten nested lists

To flatten a nested list, you can use deep flattening. For deep flattening lists within lists, use the given below code:

Also, you can use the recursive function as we did above.

A list of tuples

Flattening a list of tuples of a single depth is the same as flattening lists within lists. For shallow flattening of tuples, use the following code:

For deep flattening, a list of tuples with varying depth (nested), you can use the code given below:

Flatten 2d array

Let’s take a 2d array of 5×5 dimensions and convert it to a flattened list. Check the following code:

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.

Let us have a look at the code:

Flatten a dictionary into a list

You can flatten a dictionary to a list using a simple for loop:

Let us have a look at the code:

Using reduce

The reduce() function is defined in the functools library. You first need to import reduce from the functools.

Let’s take a look at the code:

We flattened lists with different shapes & types in different ways. I hope you find the tutorial useful. Keep coming back.

Thank you.



, , , , , , ,

0 0 Oylar
Article Rating

Bu site, istenmeyenleri azaltmak için Akismet kullanıyor. Yorum verilerinizin nasıl işlendiği hakkında daha fazla bilgi edinin.

0 Yorum
Inline Feedbacks
View all comments
Yorum yapar mısınız?x