List Comprehension with Nested For Loops


List Comprehension with Nested For Loops

List Comprehension can be written with nested for loops.

Consider the following nested for loops.

for i in x:
    for k in y:
        #append (i, k) to list

The above code can be written using List Comprehension as

[(i,k) for i in x for k in y]

Example

In the following program, we take a two lists: x and y. x is a list of some odd numbers, and y is a list of some even numbers. Iterate over elements of x using a For Loop. Inside this For Loop write a For Loop to iterate over the elements of y. This nested For Loop is placed in List Comprehension to create a list of tuples (element from x, element from y).

Python Program

x = [1, 3, 5, 7]
y = [2, 4, 6, 8]

output = [(i,k) for i in x for k in y]
print(output)

Output

[(1, 2), (1, 4), (1, 6), (1, 8), (3, 2), (3, 4), (3, 6), (3, 8), (5, 2), (5, 4), (5, 6), (5, 8), (7, 2), (7, 4), (7, 6), (7, 8)]

The equivalent code using For Loops without List Comprehension would be as shown in the following.

Python Program

x = [1, 3, 5, 7]
y = [2, 4, 6, 8]

output = []
for i in x:
    for k in y:
        output.append((i,k))

print(output)

Output

[(1, 2), (1, 4), (1, 6), (1, 8), (3, 2), (3, 4), (3, 6), (3, 8), (5, 2), (5, 4), (5, 6), (5, 8), (7, 2), (7, 4), (7, 6), (7, 8)]

Reference tutorials for the above program

Summary

In this Python Examples tutorial, we learned how to use List Comprehension with Nested For Loop.