What’s up with the comma operator’s precedence in Python?


Operator precedence determines the grouping of terms in an expression and decides how an expression is evaluated. The comma is not an operator in Python; therefore, the precedence concept doesn’t work here.

Before moving further, let us first see the precedence of operators in Python from highest precedence to lowest.

S.No. Operator & Desc
1

**

Exponentiation (raise to the power)

2

~ + -

Complement, unary plus and minus (method names for the last two are +@ and -@)

3

* / % //

Multiply, divide, modulo and floor division

4

+ -

Addition and subtraction

5

<< >>

Right and left bitwise shift

6

&

Bitwise 'AND'

7

^ |

Bitwise exclusive `OR' and regular `OR'

8

<= < > >=

Comparison operators

9

<> == !=

Equality operators

10

= %= /= //= -= += *= **=

Assignment operators

11

is is not

Identity operators

12

in not in

Membership operators

13

not or and

Logical operators

Now, let us discuss about the comma.

Example

Let’s say we have the following expressions and we need to decide how it works and calculates −

print("x" in "y", "x")

Output

False x

Example

We got the above output since the comma is not an operator, but a separator between expressions. The above is evaluated as if you had entered −

("x" in "y"), "x"

The above isn’t evaluated like this −

"x" in ("y", "x")

Updated on: 19-Sep-2022

490 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements