Flatten a Nested List in Python Using Nested for Loops

(Last Updated On: 18/01/2023)

Python Program to Flatten a Nested List Using Nested for Loops

#Flatten a Nested List in python Using Nested for Loops

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

# Create an empty list
flat_list = []

# Access each element of the sublist using a nested loop 
for sublist in my_list:
    for num in sublist:
        # append that element to flat_list
        flat_list.append(num)

# 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 *