8 Ways to Flatten a List in Python With Examples

Hello programmers, in today’s article, we will be discussing different ways to flatten a list in python. We will be learning about 8 distinct ways to flatten multidimensional or nested lists into single-dimensional ones. Out of all ways that we will be going through, you can choose the process you like the best Рeasy and needful for your program.

Before we start with different ways to flatten lists in python, let me just brief you about what a list is and what do we mean by flattening a list.  

List –  List in Python is collecting any number of different items in the order and mutable. The list is created by placing all its elements inside square brackets[], separated by a comma. The items may be of different data types, i.e., a list might have an integer, float, and string items together. A list that has another list as its items is called a nested list.

A simple list in Python :-

X = [1, 3, 5]

A nested list:

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

Flattening a list in python – Flattening lists in python means converting multidimensional lists into one-dimensional lists. It is basically a method of merging all the sublists of a nested list into one unified list. For example, the flattened list of the nested list Y = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] is given as Y = [1, 2, 3, 4, 5, 6, 7, 8, 9]

In this tutorial we will be discussing in details the 8 Different ways to flatten list in python:

  1. Shallow Flattening
  2. List Comprehension
  3. Deep Flattening
  4. Recursion method
  5. Without Recursion
  6. With Itertools
  7. Using Reduce Function
  8. NumPy Functions

1. Flatten List in Python Using Shallow Flattening:

Example:

A = [[0,1],[2,3]]

flatten_list = []

for subl in l:

    for item in subl:

        flatten_list.append(item)

print(flatten_list)

Output:

[0, 1, 2, 3]

Explanation:

This simple example flattens a list of lists by converting [[0, 1], [2, 3]] into [0, 1, 2, 3]. The method in the above example of flattening a list is called shallow flattening. It is only used with a list of lists having the same depth.

2. Flatten List in Python Using List Comprehension:

Example:

A = [[0,1], [2,3]]

flatten_list = [item for subl in l for item in subl]

print(flatten_list)

Output:

[0, 1, 2, 3]

Explanation:

Using list comprehension is a method of flattening lists in a single line of code. If we break the code, it basically comprises of a nested for loop. The first loop is ‘for a sub in l’ and the second loop is ‘for an item in sub’.

3. Flatten List in Python Using Deep Flattening:

Example:

from iteration_utilities import deepflatten

multi_depth_list = [[0,1], [[5]], [6,4]]

flatten_list = list(deepflatten(multi_depth_list))

print(flatten_list)

Output:

[0, 1, 5, 6, 4]

Explanation:

The deep Flattening method provides flattening of a list of lists having varying depths. If shallow flattening were used for the above example, it would give the output [0, 1, [5], 6, 4]. This is not our desired output, so the deep flattening method is used, which overcomes the shallow flattening method’s drawback. There is a built-in function called deepflatten() in the iteration_utilities library, enabling you to implement this method to flatten the list. However, to implement this deepflatten() function in your program, you need to install the iteration_utilities package from pip as it not available in python by default.

4. Flatten List in Python Using Recursion Method:

Example:

def flatten(l1) 
if len(l1) == 1:

  if type(l1[0]) == list:
  result = flatten(l1[0])

 else:
result = l1

#recursive case

elif type(l1[0]) == list:
result = flatten(l1[0]) + flatten(l1[1:])
else:
result = (l1[0]) + flatten(l1[1:])
return result
list1 = [[0,1], [[5]], [6, 7]]
flatten(list1)

Output:

[0, 1, 5, 6, 7]

Explanation:

Here we are using the recursion method to flatten the list. In this example, we call the function recursively inside itself to run till the end. The base case in the above example checks if the length is 1. If it’s true, it then checks whether the type of the first index of the list is a list. Only if it’s true, it calls the function to flatten the list or else stores it as an ordinary number.

5. Flatten List in Python Using Without Recursion:

Example:

def flatten_without_rec(non_flat):
    
    flat = []
    
    while non_flat: #runs until the given list is empty.
        
            e = non_flat.pop()
            
            if type(e) == list: #checks the type of the poped item.
                
                    non_flat.extend(e) #if list extend the item to given list.
            else:
                
                    flat.append(e) #if not list then add it to the flat list.
            
    flat.sort()
    
    return flat
l= [[0, 1], [[5]], [6, 7]]
flatten_without_rec(l)

Output:

[0, 1, 5, 6, 7]

Explanation:

To Flatten without Recursion, we define a function called flatten_without_rec(). This function runs the while loop until all the elements are popped out of the nested list of variable depth. The control enters the while loop till the given list becomes emp. Once it gets into the loop, it checks the type of item popped out of the list. If the item is a list, then the loop is again to be run over it. If not, then it is added to the flat list.

6. Flatten List in Python With Itertools:

Example:

import itertools

List_1 = [[1,2,3],[4,5,6],[7,8,9]] #List to be flattened

List_flat = list(itertools.chain(*List_1))

print(List_flat)

Output:

[1,2,3,4,5,6,7,8,9]

Explanation:

Importing itertools to your python program gives you access to its in-built function called itertools.chain(), which merges various lists of the nested list into a unified list. The 2-D list to be flattened is passed as an argument to the itertools.chain() function.

7. Flatten List in Python Using Reduce Function:

Example:

from functools import reduce

multi_depth_list = [[3,2,1],[1,4,5]]

reduce(list.__add__, (list(items) for items in multi_depth_list

Output:

[3,2,1,1,4,5]

Explanation:

This is a very simple way of flattening lists by using a function named reduce(). This function is a built-in function of the functools library. You will just have to import the reduction from the functools.

8. Flatten List in Python Using NumPy Functions:

The NumPy library has three built in functions that can convert nested list and multi dimensional arrays into flattend lists. The three functions are : numpy.ravel(), numpy.flatten(), numpy.reshape(-1).

numpy.ravel()

import numpy as np

list1 = np.array([[3,2,1], [4,5,6], [7,8,9]])

out = list1.ravel()

print(out)

numpy.flatten()

import numpy as np

lst = np.array([[3,2,1], [4,5,6], [7,8,9]])

out = lst.flatten()

print(out)

numpy.reshape(-1)

import numpy as np

lst = np.array([[3,2,1], [4,5,6], [7,8,9]])

out = lst.reshape(-1)

print(out)

Here the output will be same because all the three function is used to flatten list in python.

Output:

[3,2,1,4,5,6,7,8,9]

Explanation:

The NumPy package is not present in the python by default. To use these builtin flattening functions of this package, you will have to install it from pip. All three functions perform the flattening of lists and return the same output. The difference lies only in their time complexities, i.e., their speed. The flatten function returns a copy every time it flattens the array. Consequently, it takes a longer time when dealt with a larger set of values.

Must Read

Conclusion:

There are multiple ways to flatten a list in python. The best way to flatten a list depends on your program’s needs and the libraries you are using. Multidimensional arrays and nested lists having varying sizes and depths are also flattened. You can use any of the above methods to flatten the list in your python program, depending upon your choice and ease.

Still have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

Happy Pythoning!

0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments