Python Program to Flatten a Nested List Ad Sponsored

ⓘ Sponsored by

Flattening a nested list means converting a list that contains one or more nested lists into a single, one-dimensional list. For example, if you have a nested list like this:

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

You can flatten it into a one-dimensional list like this:

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

Python Code :

The below Python program flattens a nested list:

# Define a nested list
nested_list = [[1, 2], [3, 4, 5], [6, 7, 8, 9]]

# Define an empty list to store the flattened list
flat_list = []

# Loop through the nested list and append each item to flat_list
for sublist in nested_list:
    for item in sublist:

# Print the flattened list


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

In this program, we first define a nested list called nested_list.

We then define an empty list called flat_list to store the flattened list.

Next, we loop through the nested list using two nested for loops. The outer loop iterates over each sublist in the nested list, while the inner loop iterates over each item in the sublist. We then append each item to the flat_list.

Finally, we print the flattened list flat_list.

Note that this program assumes that the nested list only contains lists as its elements. If there are other data types in the nested list, the program would need to be modified to handle those cases appropriately. Ad Sponsored

ⓘ Sponsored by