Last Updated : 23 Jul, 2025
List comprehension allows us to generate new lists based on existing ones. Sometimes, we need to work with two lists together, performing operations or combining elements from both. Let's explore a few methods to use list comprehension with two lists.
Using zip() with List ComprehensionOne of the most common tasks is to apply conditions to two lists. We can use list comprehension and zip() to filter or modify elements based on conditions.
Python
a = [1, 2, 3, 4]
b = [5, 6, 7, 8]
# Create a new list where elements are from both lists, and the sum is greater than 10
result = [x + y for x, y in zip(a, b) if x + y > 10]
print(result)
Explanation:
zip(a, b)
pairs corresponding elements from both lists.if x + y > 10
filters out pairs where the sum is not greater than 10.x
and y
when the condition is met.Note: zip() with List Comprehension can be used without using any conditional statements as well.
Let's explore some more ways to use list comprehension with two Lists
Using enumerate()In some cases we may want to access the index of the elements from the lists. enumerate()
function can be used in list comprehension to iterate through both the index and the element of each list.
a = ['Python', 'is', 'fun!']
b = ['Learn', 'with', 'GFG']
# Use enumerate to get the index and pair the elements from both lists
result = [(i, x, y) for i, (x, y) in enumerate(zip(a, b))]
print(result)
[(0, 'Python', 'Learn'), (1, 'is', 'with'), (2, 'fun!', 'GFG')]
Explanation:
enumerate(zip(a, b))
gives both the index i
and the pair (x, y)
of corresponding elements from the lists a
and b
.We can also use a custom function to process the elements from two lists. This can be helpful when we need to apply a specific operation or transformation to each pair of elements.
Python
a = [1, 2, 3]
b = [4, 5, 6]
# Define a custom function to add two numbers
def add_numbers(x, y):
return x + y
# Apply the custom function to each pair of elements
result = [add_numbers(x, y) for x, y in zip(a, b)]
print(result)
Explanation:
zip(a, b)
pairs corresponding elements from the two lists.add_numbers(x, y)
is applied, which adds the two numbers.List comprehension can also handle situations where we need to loop through each element of the first list and compare it with all elements of the second list. This can be done using nested loops within the list comprehension.
Python
a = [1, 2, 3]
b = [4, 5]
# Create a new list that multiplies every element in a with every element in b
result = [x * y for x in a for y in b]
print(result)
[4, 5, 8, 10, 12, 15]
Explanation:
a
and the inner loop iterates over list b
.x
and y
, the product x * y
is added to the result list.RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4