Skip to content

Python3 Operators


This chapter mainly explains Python operators.

A simple example:

4 + 5 = 9

In this example, 4 and 5 are called operands, and + is called an operator.

Python supports the following types of operators:

Let’s learn Python’s operators one by one.


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
>>> 9//2
4
>>> -9//2
-5

The following example demonstrates the operation of all Python arithmetic operators:

#!/usr/bin/python3
 
a = 21
b = 10
c = 0
 
c = a + b
print ("1 - c value:", c)
 
c = a - b
print ("2 - c value:", c)
 
c = a * b
print ("3 - c value:", c)
 
c = a / b
print ("4 - c value:", c)
 
c = a % b
print ("5 - c value:", c)
 
# Modify variables a, b, c
a = 2
b = 3
c = a**b 
print ("6 - c value:", c)
 
a = 10
b = 5
c = a//b 
print ("7 - c value:", c)

The above example outputs:

1 - c value: 31
2 - c value: 11
3 - c value: 210
4 - c value: 2.1
5 - c value: 1
6 - c value: 8
7 - c value: 2

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:

#!/usr/bin/python3
 
a = 21
b = 10
c = 0
 
if ( a == b ):
   print ("1 - a equals b")
else:
   print ("1 - a does not equal b")
 
if ( a != b ):
   print ("2 - a does not equal b")
else:
   print ("2 - a equals b")
 
if ( a < b ):
   print ("3 - a is less than b")
else:
   print ("3 - a is greater than or equal to b")
 
if ( a > b ):
   print ("4 - a is greater than b")
else:
   print ("4 - a is less than or equal to b")
 
# Modify the values of variables a and b
a = 5
b = 20
if ( a <= b ):
   print ("5 - a is less than or equal to b")
else:
   print ("5 - a is greater than b")
 
if ( b >= a ):
   print ("6 - b is greater than or equal to a")
else:
   print ("6 - b is less than a")

The above example outputs:

1 - a does not equal b
2 - a does not equal b
3 - a is greater than or equal to b
4 - a is greater than b
5 - a is less than or equal to b
6 - b is greater than or equal to a

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:

if (n := len(a)) > 10:
    print(f"List is too long ({n} elements, expected <= 10)")

The following example demonstrates the operation of all Python assignment operators:

#!/usr/bin/python3
 
a = 21
b = 10
c = 0
 
c = a + b
print ("1 - c value:", c)
 
c += a
print ("2 - c value:", c)
 
c *= a
print ("3 - c value:", c)
 
c /= a 
print ("4 - c value:", c)
 
c = 2
c %= a
print ("5 - c value:", c)
 
c **= a
print ("6 - c value:", c)
 
c //= a
print ("7 - c value:", c)

The above example outputs:

1 - c value: 31
2 - c value: 52
3 - c value: 1092
4 - c value: 52.0
5 - c value: 2
6 - c value: 2097152
7 - c value: 99864

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:

# Traditional approach
n = 10
if n > 5:
    print(n)

# Using the walrus operator
if (n := 10) > 5:
    print(n)
  • 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 variable n a value of 10 and simultaneously returns this assignment result.
    • > 5: Checks whether the assigned n is 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 variable n (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 the if statement. The approach using the walrus operator allows direct assignment and conditional checking within the if statement.

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:

a = 0011 1100

b = 0000 1101

-----------------

a&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a  = 1100 0011
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:

#!/usr/bin/python3
 
a = 60            # 60 = 0011 1100 
b = 13            # 13 = 0000 1101 
c = 0
 
c = a & b        # 12 = 0000 1100
print ("1 - c value:", c)
 
c = a | b        # 61 = 0011 1101 
print ("2 - c value:", c)
 
c = a ^ b        # 49 = 0011 0001
print ("3 - c value:", c)
 
c = ~a           # -61 = 1100 0011
print ("4 - c value:", c)
 
c = a << 2       # 240 = 1111 0000
print ("5 - c value:", c)
 
c = a >> 2       # 15 = 0000 1111
print ("6 - c value:", c)

The above example outputs:

1 - c value: 12
2 - c value: 61
3 - c value: 49
4 - c value: -61
5 - c value: 240
6 - c value: 15

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:

#!/usr/bin/python3
 
a = 10
b = 20
 
if ( a and b ):
   print ("1 - Both variables a and b are true")
else:
   print ("1 - One of variables a and b is not true")
 
if ( a or b ):
   print ("2 - Both variables a and b are true, or one of them is true")
else:
   print ("2 - Neither variable a nor b is true")
 
# Modify the value of variable a
a = 0
if ( a and b ):
   print ("3 - Both variables a and b are true")
else:
   print ("3 - One of variables a and b is not true")
 
if ( a or b ):
   print ("4 - Both variables a and b are true, or one of them is true")
else:
   print ("4 - Neither variable a nor b is true")
 
if not( a and b ):
   print ("5 - Both variables a and b are false, or one of them is false")
else:
   print ("5 - Both variables a and b are true")

The above example outputs:

1 - Both variables a and b are true
2 - Both variables a and b are true, or one of them is true
3 - One of variables a and b is not true
4 - Both variables a and b are true, or one of them is true
5 - Both variables a and b are false, or one of them is false

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:

#!/usr/bin/python3
 
a = 10
b = 20
list = [1, 2, 3, 4, 5 ]
 
if ( a in list ):
   print ("1 - Variable a is in the given list")
else:
   print ("1 - Variable a is not in the given list")
 
if ( b not in list ):
   print ("2 - Variable b is not in the given list")
else:
   print ("2 - Variable b is in the given list")
 
# Modify the value of variable a
a = 2
if ( a in list ):
   print ("3 - Variable a is in the given list")
else:
   print ("3 - Variable a is not in the given list")

The above example outputs:

1 - Variable a is not in the given list
2 - Variable b is not in the given list
3 - Variable a is in the given list

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:

#!/usr/bin/python3
 
a = 20
b = 20
 
if ( a is b ):
   print ("1 - a and b have the same identity")
else:
   print ("1 - a and b do not have the same identity")
 
if ( id(a) == id(b) ):
   print ("2 - a and b have the same identity")
else:
   print ("2 - a and b do not have the same identity")
 
# Modify the value of variable b
b = 30
if ( a is b ):
   print ("3 - a and b have the same identity")
else:
   print ("3 - a and b do not have the same identity")
 
if ( a is not b ):
   print ("4 - a and b do not have the same identity")
else:
   print ("4 - a and b have the same identity")

The above example outputs:

1 - a and b have the same identity
2 - a and b have the same identity
3 - a and b do not have the same identity
4 - a and b do not have the same identity

Difference between is and ==:

is is used to determine whether two variables reference the same object. == is used to determine whether the values of the referenced variables are equal.

>>>a = [1, 2, 3]
>>> b = a
>>> b is a 
True
>>> b == a
True
>>> b = a[:]
>>> b is a
False
>>> b == a
True

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

(expressions...),

[expressions...], {key: value...}, {expressions...}

Parenthesized expressions

x[index], x[index:index], x(arguments...), x.attribute

Subscription, slicing, call, attribute reference

await x

await expression

**

Exponentiation

+x, -x, ~x

Positive, negative, bitwise NOT

*, @, /, //, %

Multiplication, matrix multiplication, division, floor division, modulo

+, -

Addition and subtraction

<<, >>

Shifts

&

Bitwise AND

^

Bitwise XOR

|

Bitwise OR

in,not in, is,is not, <, <=, >, >=, !=, ==

Comparisons, including membership tests and identity tests

not x

Boolean NOT

and

Boolean AND

or

Boolean OR

if -- else

Conditional expression

lambda

Lambda expression

:=

Assignment expression

The following example demonstrates the operation of all Python operator precedence:

#!/usr/bin/python3
 
a = 20
b = 10
c = 15
d = 5
e = 0
 
e = (a + b) * c / d       #( 30 * 15 ) / 5
print ("(a + b) * c / d result:",  e)
 
e = ((a + b) * c) / d     # (30 * 15 ) / 5
print ("((a + b) * c) / d result:",  e)
 
e = (a + b) * (c / d)    # (30) * (15/5)
print ("(a + b) * (c / d) result:",  e)
 
e = a + (b * c) / d      #  20 + (150/5)
print ("a + (b * c) / d result:",  e)

The above example outputs:

(a + b) * c / d result: 90.0
((a + b) * c) / d result: 90.0
(a + b) * (c / d) result: 90.0
a + (b * c) / d result: 50.0

and has higher precedence:

x = True
y = False
z = False
 
print("Case 1: Default precedence (and evaluated first)")
if x or y and z:  # Equivalent to x or (y and z)
    print("yes")  # Will be output
else:
    print("no")
 
print("\nCase 2: Forced precedence change (or evaluated first)")
if (x or y) and z:  # Artificially added parentheses to change order
    print("yes")  # Will not be output
else:
    print("no")  # Will be output

The above example first evaluates y and z and returns False, then x or False returns True. Output:

Case 1: Default precedence (and evaluated first)
yes

Case 2: Forced precedence change (or evaluated first)
no

Note: Python3 no longer supports the <> operator. You can use != instead. If you must use this comparison operator, you can use the following approach:

>>> from __future__ import barry_as_FLUFL
>>> 1 <> 2
True

Exercises