Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Continue if else in inline for Python

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
like image 386
chuseuiti Avatar asked Jun 15 '17 19:06

chuseuiti


2 Answers

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']
like image 178
Maurice Meyer Avatar answered Oct 15 '22 23:10

Maurice Meyer


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']
>>>
like image 30
Christian Dean Avatar answered Oct 15 '22 21:10

Christian Dean