Python List Comprehension with Two Lists


List Comprehension with Two Lists

Python List Comprehension is a way of creating Python Lists. List Comprehension is more idiomatic and concise when compared to looping statements, in creating lists.

In this tutorial, we will learn how to use List Comprehension with Two Lists and create a new list.

Syntax

Following is the syntax of List Comprehension with two lists.

[ expression for x in list_1 for y in list_2 ]

where expression can contain variables x and y.

The first for loop iterates for each element in list_1, and the second for loop iterates for each element in list_2.

The above list comprehension is equivalent to the following code using nested for loops.

for x in list_1:
    for y in list_2:
        expression

So, the list comprehension with two lists generates a list with number of elements equal to the product of lengths of the two lists.

Examples

1. List Comprehension using two lists

In the following example, we shall take two lists, and generate a new list using list comprehension.

Python Program

list_1 = [2, 6, 7, 3]
list_2 = [1, 4, 2]

list_3 = [ x * y for x in list_1 for y in list_2 ]

print(list_3)

Output

[2, 8, 4, 6, 24, 12, 7, 28, 14, 3, 12, 6]

Explanation

[ x * y for x in [2, 6, 7, 3] for y in [1, 4, 2] ]
 = [2 * [1, 4, 2], 6 * [1, 4, 2], 7 * [1, 4, 2], 3 * [1, 4, 2]]
 = [2, 8, 4, 6, 24, 12, 7, 28, 14, 3, 12, 6]

2. Permutations of items in two lists using List Comprehension

In the following example, we shall take two lists, and generate permutations of items in these two lists.

Python Program

list_1 = [1, 2, 3]
list_2 = ['a', 'b', 'c']

list_3 = [ (x, y) for x in list_1 for y in list_2 ]

print(list_3)

Output

[(1, 'a'), (1, 'b'), (1, 'c'), (2, 'a'), (2, 'b'), (2, 'c'), (3, 'a'), (3, 'b'), (3, 'c')]

Summary

In this tutorial of Python Examples, we learned how to use list comprehension for two lists to generate a new list.