Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't python support 'pass' in ternary expression?

Tags:

python

I've written the following code which results in SyntaxError: invalid syntax:

self.vec.append(v1) if v1 else pass

I thought it would do the same thing as this code:

if v1:
    self.vec.append(v1)

Just wondering why python does not support this syntax while it supports:

self.vec.append(v1) if v1 else 0 
like image 677
Pythoner Avatar asked Jul 17 '18 20:07

Pythoner


People also ask

Does Python support ternary operator?

Practical Data Science using PythonMany programming languages support ternary operator, which basically define a conditional expression. Similarly the ternary operator in python is used to return a value based on the result of a binary condition.

Why we should not use ternary operator?

Except in very simple cases, you should discourage the use of nested ternary operators. It makes the code harder to read because, indirectly, your eyes scan the code vertically. When you use a nested ternary operator, you have to look more carefully than when you have a conventional operator.

Is ternary faster than if-else Python?

Python ternary operator is the most efficient and faster way to perform the simple conditional statement. It returns the specific block of code depending on whether the condition is true or false.

How can the ternary operators be used in Python give an example?

Ternary Python with Numerical Values In our code, we assign the value 22 to the variable age . We use a ternary operator to check if the value of the age variable is less than 65. Because our customer is 22, the statement age < 65 evaluates to True.


1 Answers

A ternary statement is of the form:

<object> = <object> if <boolean expression> else <object>

But pass is not an <object>!

pass is a keyword, and it is used for flow control (NOOP). For instance, you can't assign pass to a variable:

>>> x = pass
Syntax Error

In the same way, you can't assign other keywords such as while to variables either:

>>> x = while
Syntax Error

Also, append returns None, which is certainly an <object>.

>>> print([].append(420))
None
like image 101
Mateen Ulhaq Avatar answered Oct 06 '22 00:10

Mateen Ulhaq