Convert List of Lists into a Flat List


Convert List of Lists into a Flat List

To convert or transform a list of lists into a flat list, where the resulting list has the elements of the inner lists as elements, use List Comprehension or List.extend() method.

The syntax to use List Comprehension to flatten a list of lists is

[x for list_i in list_of_lists for x in list_i]

The syntax to use List.extend() method to flatten a list of lists is

output = []
for e in list_of_lists:
    output.extend(e)

Examples

1. Flatten given List of Lists

In the following program, we take a list of lists, and use list comprehension to flatten a list of lists.

Python Program

list_of_lists = [
    ["apple", "banana", "cherry"],
    [25, "mango", 44, 10],
    ["red", "green", "blue"]
]

output = [x for list_i in list_of_lists for x in list_i]
print(output)

Output

['apple', 'banana', 'cherry', 25, 'mango', 44, 10, 'red', 'green', 'blue']

2. Flatten given List of Lists using List.extend() Method

In the following program, we take a list of lists, and use List.extend() method to flatten a list of lists.

Iterate over each list in the list of lists, and extend the output list with each list in the for loop.

Python Program

list_of_lists = [
    ["apple", "banana", "cherry"],
    [25, "mango", 44, 10],
    ["red", "green", "blue"]
]

output = []
for e in list_of_lists:
    output.extend(e)

print(output)

Output

['apple', 'banana', 'cherry', 25, 'mango', 44, 10, 'red', 'green', 'blue']

Summary

In this Python Examples tutorial, we learned how to convert a list of lists into a single flattened list, using different approaches like list compression, and List.extend() method.