Home > front end >  `pass` giving syntax error with ternary operator
`pass` giving syntax error with ternary operator

Time:09-26

I am able to successfully execute the below conditional expression

[i if i%2 != 0 else None for i in range(10)]

Output:

[None, 1, None, 3, None, 5, None, 7, None, 9]

However, I don't want to add None and keep only the odd numbers in the list.

To achieve that, I am executing the below code:

[i if i%2 != 0 else pass for i in range(10)]

The above statement is throwing an error:

SyntaxError: invalid syntax

What is the problem here with using pass? Why pass cannot be the operand of a ternary operator?

CodePudding user response:

The problem is that pass is not returning a value and cannot be the operand of a ternary operator. Given that your intention is to just get the odd numbers in why don't you simply iterate using a step of two

[i for i in range(1, 10, 2)]

CodePudding user response:

[i for i in range(10) if i%2 !=0] is the filter syntax you're looking for

**It's worth noting if you're doing something like creating odds (I assume your actual use is more complex) I'd use something like list(range(1,n,2)) where range takes in range(start, stop, step)

  • Related