Flatten a List of Lists in Python

Here are two ways to flatten a list of lists in Python:

(1) Using a List Comprehension:

flatten_list = [i for s in list_of_lists for i in s]

(2) Using a For Loop:

flatten_list = []

for s in list_of_lists:
for i in s:
flatten_list.append(i)

Examples

Example 1: Flatten a list of lists in Python using a List Comprehension

Assume that you have the following list of lists in Python that contains numeric data:

list_of_lists = [[11, 22, 33], [44, 55, 66], [77, 88, 99]]

print(list_of_lists)

Here is how the list of lists would look like:

[[11, 22, 33], [44, 55, 66], [77, 88, 99]]

You can then flatten the above list of lists using a List Comprehension:

list_of_lists = [[11, 22, 33], [44, 55, 66], [77, 88, 99]]

flatten_list = [i for s in list_of_lists for i in s]

print(flatten_list)

You’ll now get the flatten list:

[11, 22, 33, 44, 55, 66, 77, 88, 99]

Example 2: Flatten a list of lists in Python using a For Loop

Alternatively, you may use a For Loop to flatten a list of lists in Python:

list_of_lists = [[11, 22, 33], [44, 55, 66], [77, 88, 99]]

flatten_list = []

for s in list_of_lists:
for i in s:
flatten_list.append(i)

print(flatten_list)

You’ll get the same flatten list:

[11, 22, 33, 44, 55, 66, 77, 88, 99]

Note that the same principles apply if your list of lists contains strings:

list_of_lists = [["aa", "bb", "cc"], ["dd", "ee", "ff"], ["gg", "hh", "ii"]]

flatten_list = []

for s in list_of_lists:
for i in s:
flatten_list.append(i)

print(flatten_list)

As you can see, the list is now flatten:

['aa', 'bb', 'cc', 'dd', 'ee', 'ff', 'gg', 'hh', 'ii']

Leave a Comment