I have been sharpening my python programming skills over the past week and came across conditional filtering for list comprehension, which proves very useful. However, to add an else clause to the if filter, python requires a different syntax, as shown below:
List comprehension filter without else clause
squares = [x**2 for x in range(20) if x % 2 == 0]
List comprehension filter with else clause
squares = [x**2 if x % 2 == 0 else x + 3 for x in range(20)]
The if-else clause had to be moved to the beginning of the list comprehension after the expression x**2
Can someone explain why this is so?
The question here if/else in a list comprehension? asks about how to do it, and that I know. My question is about why it is so.
It's a slight misconception on your part.
Your first line is list comprehension with a filter. It builds a list of squares of x for only those xs for which x % 2 == 0.
Your second line is NOT list comprehension with a filter. It's just ordinary unfiltered list comprehension using the ternary operator. In this case, it's not a clause, but an expression. It says: For every x in range(20), evaluate this expression and put the resulting value in the list.
Despite the re-use of the keyword if, there is no relationship between the if statement, a conditional expression, or the filtering clause of a list comprehension.
The filter could just as easily have used a different keyword to emphasize this, for example,
[x**2 for x in range(20) aslongas x % 2 == 0]
as could the conditional expression
[x**2 when x % 2 == 0 otherwise x + 3 for x in range (20)]
But both to avoid unnecessary burden on the programmer's memory and to avoid rescinding previously valid identifier names, keywords are reused as much as possible when adding new syntactic constructs. New keywords are introduced only when the grammar prohibits the different uses being recognized unambiguously and when the benefit outweighs the potential to break existing code.
Note that your second one has no filtering; every value of x from the iterable is considered; only the value produced from x is conditional.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With