Python Program to Flatten a Nested List – 2024

Hey guys, in this blog we will see a Python Program to Flatten a Nested List.

Example 1: Using List Comprehension

# Python Program to Flatten a Nested List Using List Comprehension

my_list = [[2,1], [1,2, 3], [1, 2, 3, 4, 5, 6, 7]]

flat_list = [num for sublist in my_list for num in sublist]
print(flat_list)

Output

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

Example 2: Using Nested for Loops (non pythonic way)

# Python Program to Flatten a Nested List Using Nested for Loops (non pythonic way)

my_list = [[2,1], [1,2, 3], [1, 2, 3, 4, 5, 6, 7]]

flat_list = []
for sublist in my_list:
    for num in sublist:
        flat_list.append(num)

print(flat_list)

Output

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

Example 3: Using itertools package

# Python Program to Flatten a Nested List Using itertools package

import itertools

my_list = [[2,1], [1,2, 3], [1, 2, 3, 4, 5, 6, 7]]

flat_list = list(itertools.chain(*my_list))
print(flat_list)

Output

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

Example 4: Using sum()

# Python Program to Flatten a Nested List Using sum()

my_list = [[2,1], [1,2, 3], [1, 2, 3, 4, 5, 6, 7]]

flat_list = sum(my_list, [])
print(flat_list)

Output

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

Example 5: Using lambda and reduce()

# Python Program to Flatten a Nested List Using lambda and reduce()

from functools import reduce

my_list = [[2,1], [1,2, 3], [1, 2, 3, 4, 5, 6, 7]]
print(reduce(lambda x, y: x+y, my_list))

Output

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

Check out our other python programming examples

Leave a Reply

Your email address will not be published. Required fields are marked *