logo

... comprehensions: nested



Notes

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]

Feedback? See an issue? Something unclear? Feel free to mention it here.



If you want to be kept up to date, consider signing up for the newsletter.