Operators are symbols that perform operations on operands. For example, in 7 + 3 = 10, the values 7 and 3 are operands, while + is the operator. Python supports the following categories of operators:
- Arithmetic operators
- Comparison (relational) operators
- Assignment operators
- Logical operators
- Bitwise operators
- Membership operators
- Identity operators
- Operator precedence
Arithmetic Operators
Assume x = 15 and y = 4 for the examples below:
| Operator | Description | Example |
|---|---|---|
+ |
Adds two operands | x + y outputs 19 |
- |
Subtracts the second operand from the first | x - y outputs 11 |
* |
Multiplies two operands or repeats a string | x * y outputs 60 |
/ |
Divides the first operand by the second (returns float) | x / y outputs 3.75 |
% |
Returns the remainder of division | x % y outputs 3 |
** |
Raises the first operand to the power of the second | y ** x is 4 to the 15th power |
// |
Floor division (rounds down to nearest integer) | 17 // 3 outputs 5; -17 // 3 outputs -6 |
Code example:
val_one = 15
val_two = 4
result = 0
result = val_one + val_two
print("Addition result:", result)
result = val_one - val_two
print("Subtraction result:", result)
result = val_one * val_two
print("Multiplication result:", result)
result = val_one / val_two
print("Division result:", result)
result = val_one % val_two
print("Modulo result:", result)
# Update values
val_one = 3
val_two = 4
result = val_one ** val_two
print("Exponentiation result:", result)
val_one = 17
val_two = 3
result = val_one // val_two
print("Floor division result:", result)
Comparison Operators
Assume num_a = 8 and num_b = 12 for the examples below:
| Operator | Description | Example |
|---|---|---|
== |
Checks if operands are equal | (num_a == num_b) returns False |
!= |
Checks if operands are not equal | (num_a != num_b) returns True |
> |
Checks if left operand is greater than right | (num_a > num_b) returns False |
< |
Checks if left operand is less than right | (num_a < num_b) returns True |
>= |
Checks if left operand is greater then or equal to right | (num_a >= num_b) returns False |
<= |
Checks if leeft operand is less than or equal to right | (num_a <= num_b) returns True |
Code example:
num_one = 8
num_two = 12
if num_one == num_two:
print("Numbers are equal")
else:
print("Numbers are not equal")
if num_one != num_two:
print("Numbers are not equal")
else:
print("Numbers are equal")
if num_one < num_two:
print("First number is smaller")
else:
print("First number is larger or equal")
if num_one > num_two:
print("First number is larger")
else:
print("First number is smaller or equal")
# Update values
num_one = 7
num_two = 7
if num_one <= num_two:
print("First number is smaller or equal")
else:
print("First number is larger")
if num_two >= num_one:
print("Second number is larger or equal")
else:
print("Second number is smaller")
Assignment Operators
Assume p = 5 and q = 9 for the examples below:
| Operator | Description | Example |
|---|---|---|
= |
Simple assignment | r = p + q assigns 14 to r |
+= |
Adds right operand to left and assigns result | r += p is equivalent to r = r + p |
-= |
Subtracts right operand from left and assigns result | r -= p is equivalent to r = r - p |
*= |
Multiplies left by right and assigns result | r *= p is equivalent to r = r * p |
/= |
Divides left by right and assigns result | r /= p is equivalent to r = r / p |
%= |
Takes modulus and assigns result | r %= p is equivalent to r = r % p |
**= |
Raises left to power of right and assigns result | r **= p is equivalent to r = r ** p |
//= |
Floor divides left by right and assigns result | r //= p is equivalent to r = r // p |
:= |
Walrus operator: assigns and returns value in expression (Python 3.8+) | if (n := len(my_list)) > 5: print(f"Length is {n}") |
Code example:
p = 5
q = 9
res = 0
res = p + q
print("Basic assignment:", res)
res += p
print("Add and assign:", res)
res *= p
print("Multiply and assign:", res)
res /= p
print("Divide and assign:", res)
res = 3
res %= p
print("Modulo and assign:", res)
res **= p
print("Exponentiate and assign:", res)
res //= p
print("Floor divide and assign:", res)
Walrus operator example:
# Traditional approach
length = 12
if length > 10:
print(f"Length is {length}")
# Using walrus operator
if (length := 12) > 10:
print(f"Length is {length}")
Bitwise Operators
Bitwise operators work on values as binary digits. Assume binary_a = 60 (binary: 00111100) and binary_b = 13 (binary: 00001101).
| Operator | Description | Example |
|---|---|---|
& |
Bitwise AND: 1 if both bits are 1 | binary_a & binary_b returns 12 (00001100) |
| ` | ` | Bitwise OR: 1 if at least one bit is 1 |
^ |
Bitwise XOR: 1 if bits are different | binary_a ^ binary_b returns 49 (00110001) |
~ |
Bitwise NOT: flips all bits | ~binary_a returns -61 (11000011 in two's complement) |
<< |
Left shift: shifts bits left, fills with 0 | binary_a << 2 returns 240 (11110000) |
>> |
Right shift: shifts bits right | binary_a >> 2 returns 15 (00001111) |
Code example:
binary_a = 60 # 00111100
binary_b = 13 # 00001101
result = 0
result = binary_a & binary_b
print("Bitwise AND:", result)
result = binary_a | binary_b
print("Bitwise OR:", result)
result = binary_a ^ binary_b
print("Bitwise XOR:", result)
result = ~binary_a
print("Bitwise NOT:", result)
result = binary_a << 2
print("Left shift:", result)
result = binary_a >> 2
print("Right shift:", result)
Logical Operators
Assume m = 6 and n = 9 for the examples below:
| Operator | Logical Expression | Description | Example |
|---|---|---|---|
and |
x and y |
Returns x if x is falsy, else returns y |
(m and n) returns 9 |
or |
x or y |
Returns x if x is truthy, else returns y |
(m or n) returns 6 |
not |
not x |
Returns True if x is falsy, False if x is truthy |
not(m and n) returns False |
Code example:
a = 6
b = 9
if a and b:
print("Both values are truthy")
else:
print("At least one value is falsy")
if a or b:
print("At least one value is truthy")
else:
print("Both values are falsy")
# Update a
a = 0
if a and b:
print("Both values are truthy")
else:
print("At least one value is falsy")
if a or b:
print("At least one value is truthy")
else:
print("Both values are falsy")
if not(a and b):
print("At least one value is falsy")
else:
print("Both values are truthy")
Membership Operators
These operators check for membership in sequences like lists, tuples, or strings.
| Operator | Description | Example |
|---|---|---|
in |
Returns True if value exists in sequence |
5 in [1,2,3,4,5] returns True |
not in |
Returns True if value does not exist in sequence |
6 not in [1,2,3,4,5] returns True |
Code example:
value_one = 3
value_two = 10
sample_list = [1, 2, 3, 4, 5]
if value_one in sample_list:
print("Value exists in list")
else:
print("Value not in list")
if value_two not in sample_list:
print("Value not in list")
else:
print("Value exists in list")
Identity Operators
These operators compare the memory identity of objects.
| Operator | Description | Example |
|---|---|---|
is |
Returns True if both refer to the same object |
x is y is equivalent to id(x) == id(y) |
is not |
Returns True if they refer to different objects |
x is not y is equivalent to id(x) != id(y) |
The id() function returns the unique memory address of an object.
Code example:
obj_a = 100
obj_b = 100
if obj_a is obj_b:
print("Same object identity")
else:
print("Different object identity")
if id(obj_a) == id(obj_b):
print("Same object identity")
else:
print("Different object identity")
obj_b = 200
if obj_a is obj_b:
print("Same object identity")
else:
print("Different object identity")
if obj_a is not obj_b:
print("Different object identity")
else:
print("Same object identity")
Difference between is and ==:
ischecks if two variables reference the same object in memory.==checks if the values of two objects are equal.
list_x = [4, 5, 6]
list_y = list_x
print(list_y is list_x) # True
print(list_y == list_x) # True
list_y = list_x.copy()
print(list_y is list_x) # False
print(list_y == list_x) # True
Operator Precedence
Operators are evaluated in the following order, from highest to lowest priority. Operators in the same row have the same priority and evaluate left-to-right (except exponentiation, which evaluates right-to-left):
| Operator | Description |
|---|---|
(expr), [expr], {key:val}, {expr} |
Parentheses, list/set/dict definitions |
obj[idx], obj[start:end], obj(args), obj.attr |
Indexing, slicing, functon calls, attribute access |
await expr |
Await expression |
** |
Exponentiation |
+expr, -expr, ~expr |
Unary positive, negative, bitwise NOT |
*, @, /, //, % |
Multiplication, matrix multiplication, division, floor division, modulo |
+, - |
Addition, subtraction |
<<, >> |
Bitwise shifts |
& |
Bitwise AND |
^ |
Bitwise XOR |
| ` | ` |
in, not in, is, is not, <, <=, >, >=, !=, == |
Membership, identity, and comparison operators |
not expr |
Logical NOT |
and |
Logical AND |
or |
Logical OR |
expr if cond else expr |
Conditional expression |
lambda |
Lambda function definition |
:= |
Assignment expression (walrus operator) |