I have not been able to find the trick to do a continue/pass on an if in a for, any ideas?. Please don't provide explicit loops as solutions, it should be everything in a one liner.
I tested the code with continue, pass and only if...
list_num=[1,3]
[("Hola" if i == 1 else continue) for i in list_num]
Output of my trials :
[("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
You can replace each item in list:
>>> ['hola' if i == 1 else '' for i in list_num]
['hola', '']
Or replace when a condition is met:
>>> ['hola' for i in list_num if i == 1]
['hola']
It is important to remember that the ternary operator is still an operator, and thus needs an expression to return. So it does make sense you cannot use statements such as continue
or pass
. They are not expressions.
However, using a statement in your list comprehension is completely unnecessary anyway. In fact you don't even need the ternary operator. Filtering items from a list is a common idiom, so Python provides special syntax for doing so by allowing you to use single if
statements in a comprehension:
>>> list_num = [1, 3]
>>> ["Hola" for i in list_num if i == 1]
['Hola']
>>>
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