Python Operators

Operators in general are special symbols or keywords that perform operations on operands (values or variables). They allow you to perform calculations, comparisons, and logical operations along with other tasks. In this article, we will explore various types of operators used in Python.

In general, mathematical operators are Unicode block containing characters or standard symbols for mathematical, logical, and set notations. These mathematical operators are used to perform mathematical, logical and set operations.

Operators in Python are used to perform operations on values, variables and constants.

Operators in Python

Multiple operators that are used in Python programming. These operators are categorized in different operator types:

S.No. #Operator TypeOperators
1Arithmetic Operators+, -, *, /, //, %, **
2Comparison Operators==, !=, >, <, >=, <=
3Logical Operatorsand, or, not
4Bitwise Operators&, |, ^, ~, <<, >>
5Assignment Operators=, +=, -=, *=, /=, //=, %=, **=
6Identity Operatorsis, is not
7Membership Operatorsin, not in
Operators with Operator Types
  • Arithmetic operators – Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, division, floor division, modulus and exponentiation.
  • Comparison operators – Comparison operators are used to compare two values like equals, not equals, greater than. less than, greater than or equals, less than or equals.
  • Logical operators – Logical operators are used to combine conditional statements with and, or, not operators.
  • Bitwise operators – Bitwise operators are used to compare numbers in binary format. Before comparison, decimal number values are converted in their binary or base 2 equivalent value.
  • Assignment operators – Assignment operators are used to assign values to variables. Equal (=) is the main assignment operator.
  • Identity operators – Identity operators are used to compare the objects for the same memory location. Multiple objects can have same values, but different memory location. Identity operators check for same object and not for their same value.
  • Membership operators – Membership operators are used to test if a value is present in a sequence object.

Arithmetic Operators

Arithmetic operators are used between two operands. Generally in Mathematics these operands are numeric numbers. But in Python, these operands can be a number, character, string, list, tuple, set, dictionary or an array. There are specific scenarios in which some operands are applied on collections and some are not.

Operator NameOperatorOperationExample
+AdditionAdds two operands12 + 23 = 35
-SubtractionSubtracts the second operand from the first23 - 12 = 11
*MultiplicationMultiplies two operands8 * 7 = 56
/DivisionDivides the first operand by the second (result is a float)9 / 4 = 2.25
//Floor DivisionDivides the first operand by the second and
returns the integer part of the quotient
9 // 4 = 2
%ModulusReturns the remainder of the division of first operand by second9 % 4 = 1
**ExponentiationRaises the first operand to the power of the second3 ** 4 = 81
Arithmetic Operators
print(30 + 40)                       # Addition of two number
print('m' + 'n')                        # Addition of two characters
print(['AWS'] + ['Python'])    # Addition of two lists

print(30 - 40)                        # Subtraction of two numbers
print({"Python", "NumPy"} - {"NumPy"})   # Subtraction between two sets

print(30 * 40)                       # Multiplication of two numbers
print('mn' * 3)                       # Multiplication on string
print(('AWS','Python') * 3)   # Multiplication on Tuple
print(['AWS','Python'] * 3)    # Multiplication on List

print(37 / 5)                         # Division of two numbers

print(37 // 5)                        # Floor Division of two numbers

print(37 % 5)                        # Modulus of two numbers

print("2 ** 3 - ", 2 ** 3)        # Exponentiation of two numbers

Program Output

70                               # Addition of 30 + 40
mn                              # Addition of 'm' + 'n'
['AWS', 'Python']        # Addition of two lists
-10                              # Subtraction of two numbers
{'Python'}                   # Subtraction of two sets
1200                          # Multiplication of two numbers
mnmnmn                  # Multiplication with string
('AWS', 'Python', 'AWS', 'Python', 'AWS', 'Python')   # Multiplication with Tuple
['AWS', 'Python', 'AWS', 'Python', 'AWS', 'Python']    # Multiplication with List
7.4                              # Division of numbers
7                                 # Floor Division of numbers
2                                 # Remainder of numbers
2 ** 3 -  8                   # Exponentiation of numbers

Arithmetic Operators Precedence

In Python, the precedence of arithmetic operators determines the order in which operations are performed in an expression.

  • Operators with higher precedence are evaluated before operators with lower precedence.
  • Some operators can have equal precedence
  • If operators have the equal precedence, they are evaluated from left to right, except for exponentiation, which is evaluated right to left.
  1. Parenthesis ()
  2. Exponentiation (**)
    • Example: 2 ** 3 ** 2 is evaluated as 2 ** (3 ** 2), resulting in 512.
  3. Unary Plus (+), Unary Minus (-)
    • Example: -3 + 2 is evaluated as (-3) + 2, resulting in -1.
  4. Multiplication (*), Division (/), Floor Division (//), Modulus (%)
    • Example: 5 * 2 // 3 is evaluated as (5 * 2) // 3, resulting in 3.
    • Example: 8 % 3 * 2 is evaluated as (8 % 3) * 2, resulting in 4.
  5. Addition (+), Subtraction (-)
    • Example: 5 + 3 - 2 is evaluated as (5 + 3) - 2, resulting in 6.

Comparison Operators

Comparison operators are used to compare two operands. Generally, in Mathematics this comparison is between two numeric numbers. In Python, this comparison is supported between numbers, strings and collection datatypes as well.

  1. == => Equal => Returns True if both operands are equal, otherwise returns False
  2. != => Not Equal => Returns True if operands are not equal, otherwise returns False
  3. > => Greater Than => Returns True if the first operand is greater than the second, otherwise returns False
  4. < => Less Than => Returns True if the first operand is less than the second, otherwise returns False
  5. >= => Greater Than or Equal To => Returns True if the first operand is greater than or equal to the second, otherwise returns False
  6. <= => Less Than or Equal To => Returns True if the first operand is less than or equal to the second, otherwise returns False
Operator NameOperatorOperationExample
==EqualTrue if both operands are equal12 == 12 => True
12 == 15=>False
!=Not EqualTrue if operands are not equal12 != 12 =>False
12 != 15 => True
>Greater ThanTrue if the first operand is greater than the second15 > 12 => True
15 > 15 => False
15 > 17 => False
<Less ThanTrue if the first operand is less than the second15 < 12 => False
15 < 15 => False
15 < 17 => True
>=Greater Than or
Equal To
True if first operand is greater than or equal to the second15 >= 12 => True
15 >= 15 => True
15 >= 17=>False
<=Less Than or
Equal To
True if first operand is less than or equal to the second15 <= 12 =>False
15 <= 15 => True
15 <= 17 => True
Comparison Operators
print(12 == 12)      # Equal operator, 12 equal to 12 => returns True
print(12 == 15)      # Equal operator, 12 not equal to 15 => returns False
print(12 != 12)       # Not Equal operator, 12 equal to 12 => returns False
print(12 != 15)       # Not Equal operator, 12 not equal to 15 => returns True
print(15 > 12)        # Greater Than, 15 greater than 12 => returns True
print(15 > 15)        # Greater Than, 15 is not greater than 15 => returns False
print(12 > 15)        # Greater Than, 12 is not greater than 15 => returns False
print(12 < 15)        # Less Than, 12 is less than 15 => returns True
print(15 < 15)        # Less Than, 15 is not less than 15 => returns False
print(15 < 12)        # Less Than, 15 is not less than 12 => returns False
print(15 >= 12)     # Greater Than Equals To, 15 is greater than 12 => returns True
print(15 >= 15)     # Greater Than Equals To, 15 is equals to 15 => returns True
print(12 >= 15)     # Greater Than Equals To, 12 is neither greater than nor equals to 15 => returns False
print(12 <= 15)     # Less Than Equals To, 12 is less than 15 => returns True
print(15 <= 15)     # Less Than Equals To, 15 is equals to 15 => returns True
print(15 <= 12)     # Less Than Equals To, 15 is neither less than nor equals to 12 => returns False

Logical Operators

Logical operators are used to make a logical decision based on the given conditions. There are three logical operators – and, or and not. Below table shows the possible result combinations for AND, OR and NOT logical operators based on two operands.

AND (and): True if both operands are true, else False

ABA and B
TrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse
AND Table

OR (or): True if at least one of the operands is true, else False

ABA or B
TrueTrueTrue
TrueFalseTrue
FalseTrueTrue
FalseFalseFalse
OR Table

NOT (not): Reverses the logical state of its operand.

Anot A
TrueFalse
FalseTrue
NOT Table

Logical operators are operated based on their precedence order => first NOT (highest precedence) is operated, then AND is operated and then OR (lowest precedence) is operated. Some examples of precedence calculation:

  • result = not True and False => First not will be calculated and then and
    • not True => False , then False and False => False
  • result = True or False and False => First and will be calculated and then or
    • False and False => False, then True or False => True
  • result = not (True or False) and True => First parenthesis will be calculated, then not and then and
    • (True or False) => True
    • then, not True and True => False and True => False
  • result = not (True and False) or True => First parenthesis will be calculated, then not and then or
    • (True and False) => False
    • then, not False or True => True or True => True

Bitwise Operators

Bitwise operators in Python are used to perform operations on binary representations of integers. These operators treat numbers as a sequence of bits and operate on them bit by bit. Binary numbers are with base 2 and decimal numbers are with base 10. Any given decimal number can be converted to binary number. Bit can be either 0 or 1.

  1. & => Bitwise AND => Compares each bit of two numbers. If both bits are 1, then result bit is 1. Otherwise, it is 0
  2. | => Bitwise OR => Compares each bit of two numbers. If at least one of the bits is 1, then result bit is 1.Otherwise, it is 0.
  3. ^ => Bitwise XOR => Compares each bit of two numbers. If the bits are different, the corresponding result bit is 1.
    If they are the same, it is 0.
  4. ~ => Bitwise NOT => Inverts all the bits of the operand. It is a unary operator, meaning it operates on a single operand.
  5. << => Left Shift => Operator shifts the bits of the first operand to the left by the number of positions specified by the second operand.New bits on the right are filled with 0.
  6. >> => Right Shift => Operator shifts the bits of the first operand to the right by the number of positions specified by the second operand. New bits on the left are filled with the sign bit (0 for positive numbers, 1 for negative numbers in two’s complement representation).
Operator NameOperatorOperationExample
&Bitwise AND1 & 1 => 1
1 & 0 => 0
0 & 1 => 0
0 & 0 => 0
5 =>00000101
12=>00001100
5&12=>00000100=>4
|Bitwise OR1 & 1 => 1
1 & 0 => 1
0 & 1 => 1
0 & 0 => 0
5 =>00000101
12=>00001100
5|12=>00001101=>13
^Bitwise XOR1 & 1 => 0
1 & 0 => 1
0 & 1 => 1
0 & 0 => 0
5 =>00000101
12=>00001100
5^12=>00001001=>9
~Bitwise NOT~1 => 0
~0 => 1
5 =>00000101
~5 =>11111010=>250
<<Left Shift0111 << 2 => 11 12=>00001100
12<<5=>110000000=>384
>>Right Shift0111 >> 2 => 01 140=>10001100
140>>5=>00000100=>4
Bitwise Operators

Assignment Operators

Assignment operators are combination of assignment and arithmetic & bitwise operators.

  • Assignment operators are created as shorthand for the combination of arithmetic and bitwise operators with equal (=) operator.
  • Assignment operator does two operations combined – First it performs the arithmetic operation with the given variable and value. Then, it assigns the new value to the same variable again.
  • Assignment operator cannot be used directly with the print statement. We first have to calculate the variable value with assignment operator, then we can print the value of that variable.

Assignment operators are essential for writing concise and efficient code, as they allow you to perform operations and update variables in a single step. Python provides multiple assignment operators in two groups.

Assignment with Arithmetic Operators

  1. = (Assign) => Assigns the value on the right to the variable on the left
  2. += (Add and Assign) => Adds the right operand to the left operand and assigns the result to the left operand.
  3. -= (Subtract and Assign) => Subtracts the right operand from the left operand and assigns the result to the left operand.
  4. *= (Multiply and Assign) => Multiplies the left operand by the right operand and assigns the result to the left operand.
  5. /= (Divide and Assign) => Divides the left operand by the right operand and assigns the result to the left operand and assigns the result to the left operand.
  6. //= (Floor Divide and Assign) => Floor divides the left operand by the right operand and assigns the result to the left operand.
  7. %= (Modulus and Assign) => Modulus using the left operand and right operand and assigns the result to the left operand.
  8. **= (Exponent and Assign) => Raises the left operand to the power of the right operand and assigns the result to the left operand.

Assignment with Bitwise Operators

  1. &= (Bitwise AND and Assign) => Bitwise AND of the left operand with the right operand and assigns the result to the left operand.
  2. |= (Bitwise OR and Assign) => Bitwise OR of the left operand with the right operand and assigns the result to the left operand.
  3. ^= (Bitwise XOR and Assign) => Bitwise XOR of the left operand with the right operand and assigns the result to the left operand.
  4. <<= (Left Shift and Assign) => Left Shift of the left operand with the right operand and assigns the result to the left operand.
  5. >>= (Right Shift and Assign) => Right Shift of the left operand with the right operand and assigns the result to the left operand.
Operator NameOperatorExample
=Assignx = 20
+=Add and Assignx += 25 => x = x + 25
-=Subtract and Assignx -= 25 => x = x – 25
*=Multiply and Assignx *= 25 => x = x * 25
/=Divide and Assignx /= 25 => x = x / 25
//=Floor Divide and Assignx //= 25 => x = x // 25
%=Modulus and Assignx %= 25 => x = x % 25
**=Exponent and Assignx **= 25 => x = x ** 25
&=Bitwise AND and Assignx &= 25 => x = x & 25
|=Bitwise OR and Assignx |= 25 => x = x | 25
^=Bitwise XOR and Assignx ^= 25 => x = x ^ 25
<<=Left Shift and Assignx <<= 5 => x = x << 5
>>=Right Shift and Assignx >>= 5 => x = x >> 5
Assignment Operators

Identity Operators

Identity operators are used to compare the memory locations of two objects to determine if they are the same object. These operators are particularly checks whether two variables refer to the same object in memory, not just whether they contain equivalent values. There are two identity operators in Python.

  1. is => The is operator returns True if the two operands refer to the same object (i.e., they have the same identity in memory).
  2. is not => The is not operator returns True if the two operands do not refer to the same object (i.e., they have different identities in memory).
list_1 = [34, 56, 78]
list_2 = list_1
list_3 = [34, 56, 78]

print(list_1 is list_2)  # True, because list_2 refers to the same object as list_1
print(list_1 is list_3)  # False, because list_3 is a different object, even though it has the same content as list_1

print(list_1 is not list_2)  # False, because list_2 refers to the same object as list_1
print(list_1 is not list_3)  # True, because list_3 is a different object, even though it has the same content as list_1

Program Output

True     # list_2 refers to the same object as list_1
False   # list_3 is a different object, even though it has the same content as list_1
False   # list_2 refers to the same object as list_1
True    # list_3 is a different object, even though it has the same content as list_1

is vs ==

  • is operator checks whether two variables point to the same object in memory, whereas the == operator checks whether the values of the two objects are equivalent.
  • is and is not are used to check whether two variables point to the exact same object in memory, which is mostly required while working with mutable objects (like lists, dictionaries, or instances of custom classes).
  • == operator is used when we need to check if two variables have equivalent values, regardless of whether they are the same object.

Identity operators helps us to understand memory management of objects in Python. This becomes more important when working with complex data structures and operations like shallow copy and deep copy.

Membership Operators

Membership operators are used to test whether a value or variable exists in a sequence like string, list, tuple, set, or dictionary. Python provides two membership operators.

  1. in => in operator returns True if specified value is present in the sequence. Otherwise, it returns False.
  2. not in => not in operator returns True if specified value is not present in the sequence. Otherwise, it returns False.
course_list = ["AWS", "Python", "DevOps"]
print("ML" in course_list)               # False, because ML does not present in the list
print("AWS" in course_list)            # True, because AWS is present in the list

print("ML" not in course_list)        # True, because ML does not present in the list
print("AWS" not in course_list)     # False, because AWS is present in the list

Program Output

False      # in operator, because ML does not present in the list
True       # in operator, because AWS is present in the list
True       # not in operator, because ML does not present in the list
False     # not in operator, because AWS is present in the list

Membership operators are generally used to iterate through the elements of a collection like list, tuple, set, dictionary, string.

Summary

In this article, we explored various operators in Python. Following sections were discussed:

Python Topics


Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *