How to flatten a nested list in Python


If you have a nested list (list of lists) in Python and you want to convert it into a single list i.e. flatten a nested list, you can try writing a recursion function.


Example 1: Using recursion function:

def flattern_nested_list(input_nested_list):
    flat_list = []
    for element in input_nested_list:
        if isinstance(element, list):
            flat_list.extend(flattern_nested_list(element)) # recursion
        else:
            flat_list.append(element)
    return flat_list


# nested list
my_nested_list = [1,2,3,4,[5,6,7,8],[[9,10],11,12]]

# calling our custom function to get flattern list
my_flat_list = flattern_nested_list(my_nested_list)

# print the result
print(my_flat_list)
Output:

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

Create flat list of nested list code example python

Example 2: Using List Comprehension:

my_nested_list = [
         ["USA", "Canada", "Mexico"], 
         ["India", "China","Japan"], 
         ["Australia", "Sweden", "France", "UK"]
    ]

flat_list = [item for sub_list in my_nested_list for item in sub_list]

print(flat_list)
Output:

['USA', 'Canada', 'Mexico', 'India', 'China', 'Japan', 'Australia', 'Sweden', 'France', 'UK']

In the above example flat_list is created using a list comprehension with nested loops. The outer loop iterates through each sub_list in the nested list, and the inner loop iterates through each item in the sub_list, appending it to the flat_list.


References:

https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org



















Copyright ยฉ Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap