It's more about python list comprehension syntax. I've got a list comprehension that produces list of odd numbers of a given range:
[x for x in range(1, 10) if x % 2]
This makes a filter - I've got a source list, where I remove even numbers (if x % 2
). I'd like to use something like if-then-else here. Following code fails:
>>> [x for x in range(1, 10) if x % 2 else x * 100]
File "<stdin>", line 1
[x for x in range(1, 10) if x % 2 else x * 100]
^
SyntaxError: invalid syntax
There is a python expression like if-else:
1 if 0 is 0 else 3
How to use it inside a list comprehension?
Just another solution, hope some one may like it :
Using: [False, True][Expression]
I was able to do this
x if y else z
is the syntax for the expression you're returning for each element. Thus you need: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:
Without a filter you need:
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: