Convert List of Lists into a Flat List in Python

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

List Comprehension to Flatten a 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)
Run

Output

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

List.extend() Method to Flatten a List of Lists

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)
Run

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.