Calmcode - comprehensions: nested

Nested

1 2 3 4 5 6 7 8 9

Comprehensions can also be used to deal with nested iteration loops.

In python you might have a nested loop.

for i in range(5):
    for j in range(i):
        print((i, j))

This can also be turned into a comprehensions.

[(i, j) for i in range(5) for j in range(i)]

Even if there are if statements in the loops.

for i in range(5):
    if i > 2:
        for j in range(i):
            if j < 2:
                print((i, j))

You can still turn this into a comprehension.

[(i, j) for i in range(5) if i > 2 for j in range(i) if j < 2]