Continue if else in inline for Python
I couldn't find a trick to continue / pipe to if, for any ideas ?. Please do not provide explicit loops as solutions, it should be all in one liner.
I've tested code with continuation, forwarding and only if ...
list_num=[1,3]
[("Hola" if i == 1 else continue) for i in list_num]
The result of my tests:
[("Hola" if i == 1 else continue) for i in list_num]
^
SyntaxError: invalid syntax
File "<stdin>", line 1
[("Hola" if i == 1 else pass) for i in list_num]
^
SyntaxError: invalid syntax
File "<stdin>", line 1
[(if i == 1: "Hola") for i in list_num]
^
SyntaxError: invalid syntax
source to share
It is important to remember that the ternary operator is still an operator and therefore needs to return an expression. So it makes sense that you can't use expressions like continue
or pass
. They are not expressions.
However, using the statement in your understanding of the list is absolutely unnecessary. In fact, you don't even need the ternary operator. Filtering items from a list is a common idiom, so Python provides a special syntax for this, allowing you to use separate expressions if
in your understanding:
>>> list_num = [1, 3]
>>> ["Hola" for i in list_num if i == 1]
['Hola']
>>>
source to share