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

      

+3


source to share


4 answers


You can replace every item in the list:

>>> ['hola' if i == 1 else '' for i in list_num]
['hola', '']

      



Or replace when the condition is met:

>>> ['hola' for i in list_num if i == 1]
['hola']

      

+5


source


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']
>>>

      

+2


source


If you want to add a guard to the list comprehension operator, it will be at the end. Also, since this is protection, there is no suggestion else

:

list_num=[1,3]
["Hola" for i in list_num if i == 1]

      

+1


source


You must use the filtering function in a list comprehension. Consider the following example:

['Hola' for i in list_num if i == 1]

      

0


source







All Articles