logo

... comprehensions.


Python has a system that might simplify your code called comprehensions. They allow you to turn your nested for loop into an amazing single line of code. In this series of videos we'll highlight some useful ways to use them.


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 getting the newsletter.