Flatten a Nested List in Python Using Itertools Package

(Last Updated On: 20/01/2023)

Python Program to Flatten a Nested List Using Itertools Package

#Flatten a Nested List in python Using itertools package

import itertools

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

#list() converts those returned values into a list.
#chain() method from itertools module returns each element of each iterable (i.e. sub lists ).
flat_list = list(itertools.chain(*my_list))
 
# Output
print(flat_list)

Output:

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

Leave a Reply

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