List Comprehension to Iterate over List of Lists in Python

List Comprehension with List of Lists

Given a list of lists, we can create or transform it into a single list from the elements of the inner lists using List Comprehension.

Consider the list of lists is in the following format.

[
  [x1, x2, x3],  #list_1
  [x4, x5, x6].  #list_2
]

The syntax to use List Comprehension to iterate over the elements in a list of lists is

[x for list_i in list_of_lists for x in list_i]

The above expression can be understood using the following pseudo code.

for list_i in list_of_lists
    for x in list_i
        x

The output of the above List Comprehension expression would be

[x1, x2, x3, x4, x5, x6]

Examples

1. Iterate over given list of lists

In the following program, we take a list of lists list_of_lists, and use list comprehension to generate a single list with the elements from the inner 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 Code Copy

Output

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

2. Iterate over given list of lists with string elements

Now, let us take a list of lists with string elements in the inner lists, and generate a list containing the lengths of the strings.

Python Program

list_of_lists = [
    ["apple", "banana", "cherry"],
    ["red", "green", "blue"]
]

output = [len(x) for list_i in list_of_lists for x in list_i]
print(output)
Run Code Copy

Output

[5, 6, 6, 3, 5, 4]

Summary

In this Python Examples tutorial, we learned how to use List Comprehension for a List of Lists.

Related Tutorials

Code copied to clipboard successfully 👍