Python Flatten List Examples [7 Methods]


Python

Author: Bashir Alam
Reviewer: Deepak Prasad

Related Searches: python flatten list, python flatten , python flatten list of lists, flatten list of lists python, flatten nested list python, flatten python, python list of lists to one list

 

Introduction to Python flatten list

A  list is considered to be one of the most flexible data structures in the Python programming language. It can contain different data types. A two-dimensional list, or 2D List, which is generally termed as a list of lists, is an object of a list where each element is a list itself. Python flattening a list is a process of transforming a two-Dimensional list into a One-Dimensional list by un-nesting every list element kept in the list of lists.

In this tutorial, we will learn about the python flatten list. We will cover various ways including nested loop, list comprehension, recursive method, sum function, and through different modules to flatten a list by solving various examples. In a nutshell, this tutorial will contain all the necessary methods and examples that are needed in order to start working with the flattening of the list.

 

Getting started with Python flatten list

As we already discussed a python flattening list refers to the process of removing a dimension from a list or in simple words it is the process of converting two dimensional Python list to a one-dimensional list. A two-dimensional list is a list that contains lists as its elements.  For example, see the example of the two-dimensional list below:

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

Notice that the above-mentioned list contains lists as its elements and the flattening is simply converting such a list into a simple one-dimensional one. For example, flattening of the above list will give us:

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

Now it is a simple list that contains all the elements of the two-dimensional list. In the following sections, we will discuss various ways to convert nested lists into a simple list.

 

Method-1: Python flatten list using Nested loop

A nested loop is a loop inside the body of the outer loop. The inner or outer loop can be any type, such as a while loop or a for loop. You can learn more about the for loop or while loop from the article on Python while loop and the Python for loop.  In this section, we learn how we can use the nested loop to flatten a python list. 

 

Example: How to make flat list using nested loop

Now let us take an example and see how we can convert a nested list into a simple list by using a nested loop. Here we will use Python for loop to iterate through the list. See the example below:

# creating empty list 
flatten_list = []
# creating list 
mylist = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# interating thorugh the outer list
for element in mylist:
    # iterating through the nested list
    for nested_element in element:
        # adding element to our list
        flatten_list.append(nested_element)
# printing 
print(flatten_list)

Output:

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

So, in the above example first, we iterate through the outer list and then each element of the nested list and appended those elements in our flatten_list.

 

Method-2: Python flatten list using list comprehension

List comprehension in Python is an easy and compact syntax for creating a list from a string or another list. It is a very concise way to create a new list by performing an operation on each item in the existing list.  You can read more about list comprehension from the article on Python list comprehension. In this section, we will learn how we can use the list comprehension method to flatten a list in Python.

 

Example: How to make flat list using list comprehension

Now let us take an example and see how we can use list comprehension to flatten a list in Python. See the example below:

# creating the nested list  
mylist = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]  
# list comprehension method in Python
# Python flatten list using list comprehension 
flatten_list = [element for sub_list in mylist for element in sub_list]  
# printing the list
print(flatten_list)

Output:

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

Notice that we have used two for loops in the list comprehension method to iterate through the nested list and created a list of all the elements from the nested list.

 

Method-3: Python flatten list using recursive method

A Python recursive function is a function defined in terms of itself via self-referential expressions. This means that the function will continue to call itself and repeat its behavior until some condition is met to return a result. It acts like a loop and exits only when the specified condition is satisfied. In this section, we will learn how we can use the Python recursive method to flatten a list.

 

Example: How to make flat list using recursive method

Now let us take an example and see how we can use the python recursive method to flatten a nested list. See the Python program below:

# Python function  
def flatten_list(nested_list):  
    # check if the nested list is empty or not
    if len(nested_list) == 0:  
        return nested_list  
    # Check if the nested lis contains list or not
    if isinstance(nested_list[0], list): 
        # calling the same function again and again 
        return flatten_list(nested_list[0]) + flatten_list(nested_list[1:])  
    # Return value
    return nested_list[:1] + flatten_list(nested_list[1:])  
# printing the return value of the recursive method
print(flatten_list([[1,2,3], [4,5,6], [7,8,9]]))  

Output:

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

So here we had used the recursive method to return flatten list from the nested list.

 

Method-4: Python flatten list using functools and operator libraries

The operator library provides the iconcat() function to perform the fundamental operation like concatenation. We can apply this function cumulatively to the data elements of a nested list, from left to right, resulting in the reduction of the nested list to a flattened list. Now let us take an example and see how we can use these python libraries to flatten nested lists.

 

Example: How to make flat list using functools and operator libraries

Before writing the python program, first, we have to import these two libraries using the import keyword. Once, we successfully imported these libraries we are good to go. See the example below:

# importing operator library 
import operator  
# importing functools library
import functools  
# nested list
nested_list = [[1,2,3],[4,5,6],[7,8,9]]
# Python flatten list using functools and operator libaries
Regular_list = functools.reduce(operator.iconcat, nested_list, [])
# printing the regualar list
print(Regular_list)  

Output:

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

In the above example, we have imported the functools library along with the operator library. Then the functools.reduce() function takes two arguments and to the items and iterate the iterable from left to right, so as to reduce the iterable to a single value. As a result, the list of lists is converted into a flattened list successfully.

 

Method-5: Python flatten list using itertools library

The itertools library provides the chain() function that allows us to transform a nested list into a single flattened list ideally. This function treats consecutive series as a single series by iterating them via the iterable passed as the parameter in a serial way. In this section, we will solve an example using this library and will convert a nested list into a simple list using itertools library.

 

Example: How to make flat list using itertools library

Now let us take an example of a nested list and then will convert it into a one-dimensional list using the itertools library. See the example below:

# importing the itertools library  
import itertools  
# defining the nested list  
nested_list = [[1, 2, 3], [4,5,6], [7,8,9]] 
# python flatten list using the itertools modlule
flatten_list = list(itertools.chain(*nested_list))  
# printing
print(flatten_list)

Output:

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

Notice that first, we have imported the itertools library and then created a nested list. We have then used the chain() function to convert the given nested list to the flattened list and print it.

 

Method-6: Python flatten list using NumPy library

NumPy is the fundamental package for scientific computing in Python. It provides various operations, including the concatenation of Two-Dimensional regular Arrays column-wise or row-wise. In this section, we will use the attribute known as flat in order to get a One-Dimensional Iterator over the array to conquer the target. But first, you have to install the NumPy library on your system if it is not installed. You can use the pip command to install NumPy

 

Example: How to make flat list using NumPy library

Now let us take an example and see how we can use the NumPy library and its flat attribute in order to flatten a list. See the example below:

# importing numpy library  
import numpy  
# creating nested list  
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]  
# Python flatten list using concatenate function along with the flat attribute  
flatten_list = list(numpy.concatenate(nested_list).flat)  
# printing
print(flatten_list)  

Output:

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

Notice that first, we had imported the NumPy library and then created a nested list. . We have then used the concatenate function of the NumPy library along with its flat attribute to flatten the elements of the nested list and concatenate them to a new flattened list.

 

Method-7: Python flatten list using the sum function

We can consider summing over inner lists as another solution to the problem. First, we need to pass two arguments to the sum function: The first parameter is iterable, which is a nested list, and the second parameter is the start of a void list for the following case that serves as the initial flat list where the data elements of the inner sub-lists will added. 

 

Example: How to make flat list using the sum function

Now let us take an example and see how we can use the sum function to flatten a python nested list. See the example below:

# creating a nested list  
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]  
# Python flatten list using the sum function  
flatten_list = sum(nested_list, [])  
# printing
print(flatten_list)  

Output:

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

Notice that in the above example, we have defined the nested list. Then we used the sum() function and flattened the nested list into a One-Dimensional list, and printed the resultant list.

 

Summary

When we convert a list of lists, or a 2-dimensional array, into a one-dimensional array, it is called flattening a list. In this tutorial, we learned about 7 different ways of flattening a nested list in Python. We covered the nested loop method, list comprehension, recursive method, sum method and also covered some Python modules which helped us to flatten the nested list. To summarize, this tutorial contains all the necessary methods and ways that are useful to flatten a list in Python along with various examples.

 

Further Reading

Python list
Numpy array flatten
Python array

 

Bashir Alam

Bashir Alam

He is a Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in Python, Java, Machine Learning, OCR, text extraction, data preprocessing, and predictive models. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment