Convert a Nested List into a Flat List in Python

How to convert a nested list into a flat list in Python? You can convert a nested list into a flat list using many ways, for example, by using the nested for loops, recursion, list comprehension, numpy module, functools module, sum(), extend(), and itertools module. In this article, I will explain how to convert a nested list into a flat list by using all these methods with examples.

1. Quick Examples of Converting the Nested List into a Flat List

If you are in a hurry, below are some quick examples of how to convert the nested list into a flat list.


# Quick examples of converting nested list into a flat

# Initialize nested list 
nested_list= [[2, 4, 6, 8], [10, 12, 14], [16, 18, 20]]

# Example 1: Using nested for loops
def flat(nested_list):
    flatList = []
    for element in nested_list:
        if type(element) is list:
            for item in element:
                flatList.append(item)
        else:
            flatList.append(element)
    return flatList

# Example 2: Using recursion
# Convert a nested list into a flat list 
nested_list= [1, 3, [5, 7, [9, 10]], 11, 13, [15, [17]]]
flatList = [] 
def reemovNestings(nested_list):
    for i in nested_list:
        if type(i) == list:
            reemovNestings(i)
        else:
            flatList.append(i)
reemovNestings(nested_list)

# Example 3: Using a list comprehension
flat_list = [element for innerList in nested_list for element in innerList]

# Example 4: Using the numpy module
flat_list = list(np.concatenate(nested_list))

# Example 5: Using the Python functools module
flat_list = functools.reduce(operator.iconcat, nested_list, [])

# Example 6: Using sum() method 
flat_list = sum(nested_list, [])

# Example 7: Using extend() method
flat_list=[]
for i in nested_list:
    flat_list.extend(i)

# Example 8: Using itertools.chain() function
flat_list = list(itertools.chain(*nested_list))

2. Convert a Nested List into a Flat List Using Nested For Loops

You can convert a nested list into a flat list using nested for loops. You can use nested for loops to iterate through the elements of the nested list and appends them to a new flat list.

In the below example, first define the flat() function which, takes a nested list as input and initializes an empty flatList. It then iterates over each element in the nested list using the first for loop. If the element is itself a list (checked using type(element) is list), it iterates over each item in that sublist using the second for loop and appends each item to the flatList. If the element is not a list, it appends the element directly to the flatList. Finally, it returns the flatList once all the elements have been appended.


# Initialize the nested list 
nested_list= [[2, 4, 6, 8], [10, 12, 14], [16, 18, 20]]
print('Nested list', nested_list)

# Using nested for loops
def flat(nested_list):
    flatList = []
    # Iterate with outer list
    for element in nested_list:
        if type(element) is list:
            # Check if type is list then iterate through the sublist
            for item in element:
                flatList.append(item)
        else:
            flatList.append(element)
    return flatList
        
print('Flat list:', flat(nested_list))

Yields below output.

python convert nested flat list

3. Convert a Nested List into a Flat List Using Recursion

You can also convert a nested list into a flat list using recursion, you can define a recursive function that handles each element of the nested list. For example, the reemovNestings function is defined to recursively handle the nested list. It initializes a local flatList variable inside the function. The function iterates over each element in the nested list and checks if it is a list. If it is a list, the function recursively calls itself with that sublist and extends the flatList with the returned value. If it is not a list, the element is appended directly to the flatList.


# Initialize nested list 
nested_list= [1, 3, [5, 7, [9, 10]], 11, 13, [15, [17]]]
print('Nested list', nested_list)

# Using recursion
# Convert a nested list into a flat list 
flatList = [] 
def reemovNestings(nested_list):
    for i in nested_list:
        if type(i) == list:
            reemovNestings(i)
        else:
            flatList.append(i)

reemovNestings(nested_list)
print('Flat list:', flatList)

Yields below output.

4. Convert a Nested List into a Flat List Using a List Comprehension

You can also convert a nested list into a flat list using list comprehension. The list comprehension iterates over each innerList in the nested_list and then iterates over each element in the innerList. It creates a new list containing all the elements from the inner lists, effectively flattening the nested list into a single flat list.


# Initialize the nested list 
nested_list= [[2, 4, 6, 8], [10, 12, 14], [16, 18, 20]]
print('Nested list', nested_list)

# Using a list comprehension
flat_list = [element for innerList in nested_list for element in innerList]
print('Flat list:', flat_list)

# Output:
# Nested list [[2, 4, 6, 8], [10, 12, 14], [16, 18, 20]]
# Flat list: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

5. Using the Numpy Module

Alternatively, you can use the np.concatenate() function from the NumPy module to flatten a nested list. For example, the np.concatenate function is used to concatenate the nested list into a single 1-D NumPy array. Then, the list function is called to convert the NumPy array into a Python list. This resulting list represents the flattened version of the nested list.


import numpy as np

# Initialize the nested list 
nested_list = [[2, 4, 6, 8], [10, 12, 14], [16, 18, 20]]
print('Nested list', nested_list)

# Using the numpy module
flat_list = list(np.concatenate(nested_list))
print('Flat list:', flat_list)

Yields the same output as above.

6. Using the Python functools Module

You can also use the functools.reduce function from the Python functools module, in combination with operator.iconcat, can be used to flatten a nested list.

In the below example, the functools.reduce function is used to concatenate each sublist within the nested_list using the operator.iconcat. The operator.iconcat function performs the concatenation of two lists. The initial value for the reduction is an empty list ([]). This process effectively flattens the nested list into a single flat list.


import functools
import operator

# Initialize the nested list 
nested_list = [[2, 4, 6, 8], [10, 12, 14], [16, 18, 20]]
print('Nested list', nested_list)

# Using the Python functools module
flat_list = functools.reduce(operator.iconcat, nested_list, [])
print('Flat list:', flat_list)

Yields the same output as above.

7. Convert a Nested List into a Flat List Using the sum() Method

Python sum() method can be used to flatten a nested list. For example, the sum() method is used with an empty list ([]) as the initial value. The sum() method takes each sublist within the nested_list and concatenates them into a single flat list. This happens because the sum() method is overloaded for lists, and when used with an empty list as the initial value, it concatenates the lists together.


# Initialize nested list 
nested_list = [[2, 4, 6, 8], [10, 12, 14], [16, 18, 20]]
print('Nested list', nested_list)

# Using sum() method 
flat_list = sum(nested_list, [])
print('Flat list:', flat_list)

Yields the same output as above.

8. Using extend() Method

You can also convert a nested list into a flat list using the extend() method. For example, you initialize an empty flat_list as an empty list. Then, you iterate over each sublist nested_list using a for loop. Within the loop, you use the extend() method to append each element from the sublist to the flat_list. The extend() method is a built-in list method that adds all the elements from an iterable (in this case, the sublist) to the list. Finally, you have flat_list with all the elements from the nested list appended to it.


# Initialize nested list 
nested_list = [[2, 4, 6, 8], [10, 12, 14], [16, 18, 20]]
print('Nested list', nested_list)

# Using extend() method
flat_list=[]
for i in nested_list:
    flat_list.extend(i)
print('Flat list:', flat_list)

Yields the same output as above.

9. Using itertools Module

You can also use the itertools module in Python provides a powerful set of functions for working with iterators and combinatorial operations. It includes the itertools.chain() function, which can be used to flatten a nested list.

In the below example, the itertools.chain() function is used with the * operator to unpack the nested_list into individual sublists. The itertools.chain() function then combines these sublists into a single iterator. Finally, the list() function is called to convert the iterator into a list, resulting in the flattened flat_list.


import itertools

# Initialize nested list 
nested_list = [[2, 4, 6, 8], [10, 12, 14], [16, 18, 20]]
print('Nested list', nested_list)

# Using itertools.chain() function
flat_list = list(itertools.chain(*nested_list))
print('Flat list:', flat_list)

Yields the same output as above.

Conclusion

In this article, I have explained how to convert the nested list into a flat list in Python by using nested for loops, recursion, list comprehension, numpy module, functools module, sum(), extend(), and itertools module with examples.

Happy Learning !!

Malli

Malli is an experienced technical writer with a passion for translating complex Python concepts into clear, concise, and user-friendly articles. Over the years, he has written hundreds of articles in Pandas, NumPy, Python, and takes pride in ability to bridge the gap between technical experts and end-users.

Leave a Reply