logo

... comprehensions: if



Notes

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 signing up for the newsletter.