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
2
  • You're returning 'continue' as the result of a ternary operation. A if B else C is a ternary operator, it evaluates B and returns A if true, C if not. Commented Jun 15, 2017 at 19:17
  • You can't use statements in conditional expressions. Commented Jun 15, 2017 at 19:18

4 Answers 4

17

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']
Sign up to request clarification or add additional context in comments.

2 Comments

Also for replacement, I'd like to offer this alternative: ["hola" * (i==1) for i in list_num]
Awesome ! Thanks for your answer, the second one is exactly what I wanted.
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']
>>>

Comments

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]

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.