Two For Loops in List Comprehension - Python
Last Updated :
03 Dec, 2024
List comprehension is a concise and readable way to create lists in Python. Using two for loops in list comprehension is a great way to handle nested iterations and generate complex lists.
Using two for-loops
This is the simplest and most efficient way to write two for loops in a list comprehension. Let's suppose we want to combine two loops inside one. We have two lists, and we want to combine their values in pairs.
Python
x = [1, 2]
y = [3, 4]
# Using two for loops inside a list comprehension
ans = [(a, b) for a in x for b in y]
print(ans)
Output[(1, 3), (1, 4), (2, 3), (2, 4)]
There are various methods to write two loops in List Comprehension in Python.
Filter Based on a Condition (Adding an if Clause)
We can also add a condition to filter the results while using two for loops. Let’s say we only want pairs where the sum of a and b is greater than 4.
Python
x = [1, 2, 3]
y = [3, 4, 5]
# Using two for loops and an if condition to filter
ans = [(a, b) for a in x for b in y if a + b > 4]
print(ans)
Output[(1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 3), (3, 4), (3, 5)]
Nested Loops with Different Range
Sometimes, we might want to generate numbers or perform a calculation based on the ranges. In such cases, using two for loops is helpful.
Python
# Generating pairs of numbers from 1 to 3 and 4 to 6
ans = [(a, b) for a in range(1, 4) for b in range(4, 7)]
print(ans)
Output[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]
Using Two Loops with a More Complex Condition
Now let’s try something a bit more complex. We want to generate pairs where a is even and b is odd.
Python
# Generating pairs with specific conditions
ans = [(a, b) for a in range(1, 6) for b in range(1, 6) if a % 2 == 0 and b % 2 != 0]
print(ans)
Output[(2, 1), (2, 3), (2, 5), (4, 1), (4, 3), (4, 5)]