How to flatten a list of lists into a list in Python

Let’s go through the different methods to flatten the following list of lists:

nested_lists = [[1, 2, 3], [4, 5, 6]]

Method 1: Nested loop

The simplest method is probably to go through an explicit double for-loop, as if you read all the values from left to right and moved them into a flat list:

flat_list = []

for inner_list in nested_lists:  # [1, 2, 3] then [4, 5, 6]
    for number in inner_list:
        flat_list.append(number)

Method 2: Reduce

Another way is to rely on the reduce method to extend an empty list by going through each of the nested lists:

from functools import reduce

reduce(lambda x, y: x + y, nested_lists)

Method 3: List Comprehension

Finally, we could do something similar to the first method, but inline:

flat_list = [entry for inner_list in nested_lists for entry in inner_list]

Comparison

These 3 methods have a time complexity of O(n*m), with n being the number of inner lists, and m the number of items in each of them. For a small list of lists, any of these methods should work just fine. But for a larger one, the list comprehension might be slightly more efficient. One reason for that is that the list comprehension generates only one list, and copies each item only once, while the other methods store intermediary results that get bigger with the list of lists. That being said, don’t trust, verify! See Measuring Execution Time for more info about measuring performance.