6

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
chuseuiti
  • 783
  • 1
  • 9
  • 32

4 Answers4

16

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']
Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47
3

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']
>>>
Christian Dean
  • 22,138
  • 7
  • 54
  • 87
1

If you want to add a guard to a list comprehension statement it goes at the end. Also, since it is a guard there is no else clause:

list_num=[1,3]
["Hola" for i in list_num if i == 1]
JohanL
  • 6,671
  • 1
  • 12
  • 26
0

You should use filtering feature in the list comprehension. Consider the following example:

['Hola' for i in list_num if i == 1]
Robson
  • 813
  • 5
  • 21
  • 40