A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python-list-comprehension-with-two-lists/ below:

Python List Comprehension With Two Lists

Python List Comprehension With Two Lists

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 Comprehension

One 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:

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.

Python
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) 

Output
[(0, 'Python', 'Learn'), (1, 'is', 'with'), (2, 'fun!', 'GFG')]

Explanation:

Using Custom Function

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:

Using Nested Loops

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)  

Output
[4, 5, 8, 10, 12, 15]

Explanation:



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