... 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.


There are two ways of using an if-statement in a comprehension. You can filter.

[i for i in range(16) if i % 2 == 0]

Alternatively you can also use an if to calculate values.

[i if i % 2 == 0 else i * 2 for i in range(16)]

You can also combine the two approaches.

[i if i % 2 == 0 else i * 2 for i in range(16) if i % 3 == 0]

Before copying/pasting, try to predict what the last line of code does.

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.