Skip to content

Python list comprehension two lists | Example code

  • by

Use two for loop or use zip() function to list comprehension two lists in Python. Here is the syntax of List Comprehension with two lists.

[ expression for x in list_1 for y in list_2 ]

Example list comprehension two lists in Python

Simple example code List Comprehension with Two Lists and create a new list.

list_1 = [1, 2, 3]
list_2 = [5, 6]

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

print(list_3)

Output:

Python list comprehension two lists

Another example using zip() method

Iterate two or more lists simultaneously within list comprehension.

list_1 = [1, 2, 3]
list_2 = [5, 6]

res = [(i, j) for i, j in zip(list_1, list_2)]

print(res)

Output: [(1, 5), (2, 6)]

Nested list comprehension with two lists

matrix = [[j for j in range(5)] for i in range(5)]

print(matrix)

Output:

[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]

Do comment if you have any doubts and suggestions on this Python list tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *