Conditional Comprehensions
The two places an if can appear in a comprehension, which does which, and why only one of them takes an else.
Overview
Filter: the trailing if
[n for n in nums if n % 2 == 0]
This drops items. Six numbers in, three out. The if sits after the for, and it takes no else — there is nowhere for an alternative to go, because a filter either keeps an item or does not.
Writing [n for n in nums if n % 2 == 0 else 0] is a syntax error, and it is worth trying once so the error message becomes familiar.
two_ifs.py
comprehension_conditions.py
Worth knowing
if = filter. It drops items and takes no else.if/else in the expression = choose. Every item survives, with one of two values.ifs mean the same as one and.