One-line list comprehension: if-else variants One-line list comprehension: if-else variants python python

One-line list comprehension: if-else variants


x if y else z is the syntax for the expression you're returning for each element. Thus you need:

[ x if x%2 else x*100 for x in range(1, 10) ]

The confusion arises from the fact you're using a filter in the first example, but not in the second. In the second example you're only mapping each value to another, using a ternary-operator expression.

With a filter, you need:

[ EXP for x in seq if COND ]

Without a filter you need:

[ EXP for x in seq ]

and in your second example, the expression is a "complex" one, which happens to involve an if-else.


You can do that with list comprehension too:

A=[[x*100, x][x % 2 != 0] for x in range(1,11)]print A