Python3 Operators
What is an Operator?
Section titled “What is an Operator?”This chapter mainly explains Python operators.
A simple example:
In this example, 4 and 5 are called operands, and + is called an operator.
Python supports the following types of operators:
- Arithmetic Operators
- Comparison (Relational) Operators
- Assignment Operators
- Logical Operators
- Bitwise Operators
- Membership Operators
- Identity Operators
- Operator Precedence
Let’s learn Python’s operators one by one.
Python Arithmetic Operators
Section titled “Python Arithmetic Operators”Assume variable a = 10 and variable b = 21:
| Operator | Description | Example |
|---|---|---|
| + | Addition - adds two objects | a + b outputs 31 |
| - | Subtraction - returns a negative number or subtracts one number from another | a - b outputs -11 |
| * | Multiplication - multiplies two numbers or returns a string repeated a number of times | a * b outputs 210 |
| / | Division - x divided by y | b / a outputs 2.1 |
| % | Modulo - returns the remainder of division | b % a outputs 1 |
| ** | Exponentiation - returns x raised to the power of y | a**b is 10 to the power of 21 |
| // | Floor division - rounds toward the smaller direction | |
The following example demonstrates the operation of all Python arithmetic operators:
Example (Python 3.0+)
Section titled “Example (Python 3.0+)”The above example outputs:
Python Comparison Operators
Section titled “Python Comparison Operators”Assume variable a is 10 and variable b is 20:
| Operator | Description | Example |
| == | Equal - compares whether objects are equal | (a == b) returns False. |
| != | Not equal - compares whether two objects are not equal | (a != b) returns True. |
| > | Greater than - returns whether x is greater than y | (a > b) returns False. |
| < | Less than - returns whether x is less than y. All comparison operators return 1 for true and 0 for false. These are equivalent to the special variables True and False. Note the capitalization of these variable names. | (a < b) returns True. |
| >= | Greater than or equal to - returns whether x is greater than or equal to y | (a >= b) returns False. |
| <= | Less than or equal to - returns whether x is less than or equal to y | (a <= b) returns True. |
The following example demonstrates the operation of all Python comparison operators:
Example (Python 3.0+)
Section titled “Example (Python 3.0+)”The above example outputs:
Python Assignment Operators
Section titled “Python Assignment Operators”Assume variable a is 10 and variable b is 20:
| Operator | Description | Example |
|---|---|---|
| = | Simple assignment operator | c = a + b assigns the result of a + b to c |
| += | Addition assignment operator | c += a is equivalent to c = c + a |
| -= | Subtraction assignment operator | c -= a is equivalent to c = c - a |
| *= | Multiplication assignment operator | c *= a is equivalent to c = c * a |
| /= | Division assignment operator | c /= a is equivalent to c = c / a |
| %= | Modulo assignment operator | c %= a is equivalent to c = c % a |
| **= | Exponentiation assignment operator | c **= a is equivalent to c = c ** a |
| //= | Floor division assignment operator | c //= a is equivalent to c = c // a |
| := | Walrus operator. The main purpose of this operator is to simultaneously assign and return the assigned value within an expression. New operator added in Python 3.8. | In this example, the assignment expression avoids calling len() twice: |
The following example demonstrates the operation of all Python assignment operators:
Example (Python 3.0+)
Section titled “Example (Python 3.0+)”The above example outputs:
In Python 3.8 and later, a new syntax feature called the “Walrus Operator” was introduced, which uses the := symbol. The main purpose of this operator is to simultaneously assign and return the assigned value within an expression.
Using the walrus operator can simplify code in some cases, especially when you need to use the assignment result within an expression. This is useful for simplifying loop conditions or avoiding repeated calculations in expressions.
Here is a simple example demonstrating the use of the walrus operator:
Example
Section titled “Example”if (n := 10) > 5:: This is the approach using the walrus operator (:=). The walrus operator performs an assignment within an expression.(n := 10): Assigns the variablena value of 10 and simultaneously returns this assignment result.> 5: Checks whether the assignednis greater than 5. If the condition is true, the following code block is executed.
print(n): If the condition is true, prints the value of variablen(i.e., 10).
Advantages of the walrus operator:
- The walrus operator (
:=) allows assignment within expressions, which can reduce code duplication and improve code readability and conciseness. - In the above example, the traditional approach requires a separate line to assign
n, and then a conditional check in theifstatement. The approach using the walrus operator allows direct assignment and conditional checking within theifstatement.
Python Bitwise Operators
Section titled “Python Bitwise Operators”Bitwise operators treat numbers as binary for calculations. The rules for bitwise operations in Python are as follows:
In the table below, variable a is 60 and b is 13. Their binary formats are:
| Operator | Description | Example |
| & | Bitwise AND operator: If both corresponding bits of the two operands are 1, the result bit is 1; otherwise, it is 0 | (a & b) outputs 12, binary: 0000 1100 |
| | | Bitwise OR operator: If either of the two corresponding bits is 1, the result bit is 1 | (a | b) outputs 61, binary: 0011 1101 |
| ^ | Bitwise XOR operator: When the two corresponding bits are different, the result is 1 | (a ^ b) outputs 49, binary: 0011 0001 |
| ~ | Bitwise NOT operator: Inverts each binary bit of the data, i.e., changes 1 to 0 and 0 to 1. ~x is similar to -x-1 | (~a) outputs -61, binary: 1100 0011, in two’s complement form of a signed binary number |
| << | Left shift operator: Shifts all binary bits of the operand to the left by the number of bits specified by the right operand. High bits are discarded, and low bits are filled with 0 | a << 2 outputs 240, binary: 1111 0000 |
| >> | Right shift operator: Shifts all binary bits of the left operand to the right by the number of bits specified by the right operand | a >> 2 outputs 15, binary: 0000 1111 |
The following example demonstrates the operation of all Python bitwise operators:
Example (Python 3.0+)
Section titled “Example (Python 3.0+)”The above example outputs:
Python Logical Operators
Section titled “Python Logical Operators”Python supports logical operators. Assume variable a is 10 and b is 20:
| Operator | Logical Expression | Description | Example |
| and | x and y | Boolean “AND” - if x is False, x and y returns the value of x; otherwise, returns the evaluated value of y | (a and b) returns 20. |
| or | x or y | Boolean “OR” - if x is True, it returns the value of x; otherwise, it returns the evaluated value of y | (a or b) returns 10. |
| not | not x | Boolean “NOT” - if x is True, returns False. If x is False, returns True | not(a and b) returns False |
The above example outputs:
Example (Python 3.0+)
Section titled “Example (Python 3.0+)”The above example outputs:
Python Membership Operators
Section titled “Python Membership Operators”In addition to the operators above, Python also supports membership operators, which test whether a value is a member of a sequence, including strings, lists, or tuples.
| Operator | Description | Example |
| in | Returns True if the value is found in the specified sequence; otherwise, returns False | x in y sequence, returns True if x is in the y sequence |
| not in | Returns True if the value is not found in the specified sequence; otherwise, returns False | x not in y sequence, returns True if x is not in the y sequence |
The following example demonstrates the operation of all Python membership operators:
Example (Python 3.0+)
Section titled “Example (Python 3.0+)”The above example outputs:
Python Identity Operators
Section titled “Python Identity Operators”Identity operators are used to compare the memory locations of two objects.
| Operator | Description | Example |
| is | is checks whether two identifiers refer to the same object | x is y, similar to id(x) == id(y), returns True if they refer to the same object; otherwise, returns False |
| is not | is not checks whether two identifiers refer to different objects | x is not y, similar to id(x) != id(y). Returns True if they do not refer to the same object; otherwise, returns False |
Note: The id() function is used to get the memory address of an object.
The following example demonstrates the operation of all Python identity operators:
Example (Python 3.0+)
Section titled “Example (Python 3.0+)”The above example outputs:
Difference between is and ==:
isis used to determine whether two variables reference the same object.==is used to determine whether the values of the referenced variables are equal.
Python Operator Precedence
Section titled “Python Operator Precedence”The following table lists all operators from highest to lowest precedence. Operators in the same cell have the same precedence. All operators are binary unless otherwise specified. Operators in the same cell group left-to-right (except for exponentiation, which groups right-to-left):
Operator |
Description |
|---|---|
|
Parenthesized expressions |
|
Subscription, slicing, call, attribute reference |
await x |
await expression |
|
Exponentiation |
|
Positive, negative, bitwise NOT |
|
Multiplication, matrix multiplication, division, floor division, modulo |
|
Addition and subtraction |
|
Shifts |
|
Bitwise AND |
|
Bitwise XOR |
|
Bitwise OR |
|
Comparisons, including membership tests and identity tests |
|
Boolean NOT |
|
Boolean AND |
|
Boolean OR |
|
Conditional expression |
|
Lambda expression |
|
Assignment expression |
The following example demonstrates the operation of all Python operator precedence:
Example (Python 3.0+)
Section titled “Example (Python 3.0+)”The above example outputs:
and has higher precedence:
Example
Section titled “Example”The above example first evaluates y and z and returns False, then x or False returns True. Output:
Note: Python3 no longer supports the
<>operator. You can use!=instead. If you must use this comparison operator, you can use the following approach: