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 Type | Operators |
---|---|---|
1 | Arithmetic Operators | +, -, *, /, //, %, ** |
2 | Comparison Operators | ==, !=, >, <, >=, <= |
3 | Logical Operators | and, or, not |
4 | Bitwise Operators | &, |, ^, ~, <<, >> |
5 | Assignment Operators | =, +=, -=, *=, /=, //=, %=, **= |
6 | Identity Operators | is, is not |
7 | Membership Operators | in, not in |
- 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 Name | Operator | Operation | Example |
---|---|---|---|
+ | Addition | Adds two operands | 12 + 23 = 35 |
- | Subtraction | Subtracts the second operand from the first | 23 - 12 = 11 |
* | Multiplication | Multiplies two operands | 8 * 7 = 56 |
/ | Division | Divides the first operand by the second (result is a float) | 9 / 4 = 2.25 |
// | Floor Division | Divides the first operand by the second and returns the integer part of the quotient | 9 // 4 = 2 |
% | Modulus | Returns the remainder of the division of first operand by second | 9 % 4 = 1 |
** | Exponentiation | Raises the first operand to the power of the second | 3 ** 4 = 81 |
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.
- Parenthesis
()
- Exponentiation (
**
)- Example:
2 ** 3 ** 2
is evaluated as2 ** (3 ** 2)
, resulting in512
.
- Example:
- Unary Plus (
+
), Unary Minus (-
)- Example:
-3 + 2
is evaluated as(-3) + 2
, resulting in-1
.
- Example:
- Multiplication (
*
), Division (/
), Floor Division (//
), Modulus (%
)- Example:
5 * 2 // 3
is evaluated as(5 * 2) // 3
, resulting in3
. - Example:
8 % 3 * 2
is evaluated as(8 % 3) * 2
, resulting in4
.
- Example:
- Addition (
+
), Subtraction (-
)- Example:
5 + 3 - 2
is evaluated as(5 + 3) - 2
, resulting in6
.
- Example:
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.
==
=> Equal => ReturnsTrue
if both operands are equal, otherwise returnsFalse
!=
=> Not Equal => ReturnsTrue
if operands are not equal, otherwise returnsFalse
>
=> Greater Than => ReturnsTrue
if the first operand is greater than the second, otherwise returnsFalse
<
=> Less Than => ReturnsTrue
if the first operand is less than the second, otherwise returnsFalse
>=
=> Greater Than or Equal To => ReturnsTrue
if the first operand is greater than or equal to the second, otherwise returnsFalse
<=
=> Less Than or Equal To => ReturnsTrue
if the first operand is less than or equal to the second, otherwise returnsFalse
Operator Name | Operator | Operation | Example |
---|---|---|---|
== | Equal | True if both operands are equal | 12 == 12 => True 12 == 15=> False |
!= | Not Equal | True if operands are not equal | 12 != 12 =>False 12 != 15 => True |
> | Greater Than | True if the first operand is greater than the second | 15 > 12 => True 15 > 15 => False 15 > 17 => False |
< | Less Than | True if the first operand is less than the second | 15 < 12 => False 15 < 15 => False 15 < 17 => True |
>= | Greater Than or Equal To | True if first operand is greater than or equal to the second | 15 >= 12 => True 15 >= 15 => True 15 >= 17=> False |
<= | Less Than or Equal To | True if first operand is less than or equal to the second | 15 <= 12 =>False 15 <= 15 => True 15 <= 17 => True |
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
A | B | A and B |
---|---|---|
True | True | True |
True | False | False |
False | True | False |
False | False | False |
OR (or
): True
if at least one of the operands is true, else False
A | B | A or B |
---|---|---|
True | True | True |
True | False | True |
False | True | True |
False | False | False |
NOT (not
): Reverses the logical state of its operand.
A | not A |
---|---|
True | False |
False | True |
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
=> Firstnot
will be calculated and thenand
not True
=>False
, thenFalse and False
=>False
result = True or False and False
=> Firstand
will be calculated and thenor
False and False
=>False
, thenTrue or False
=>True
result = not (True or False) and True
=> First parenthesis will be calculated, thennot
and thenand
(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, thennot
and thenor
(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
.
&
=> Bitwise AND => Compares each bit of two numbers. If both bits are1
, then result bit is1
. Otherwise, it is0
|
=> Bitwise OR => Compares each bit of two numbers. If at least one of the bits is1
, then result bit is1
.Otherwise, it is0
.^
=> Bitwise XOR => Compares each bit of two numbers. If the bits are different, the corresponding result bit is1
.
If they are the same, it is0
.~
=> Bitwise NOT => Inverts all the bits of the operand. It is a unary operator, meaning it operates on a single operand.<<
=> 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 with0
.>>
=> 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 Name | Operator | Operation | Example |
---|---|---|---|
& | Bitwise AND | 1 & 1 => 1 1 & 0 => 0 0 & 1 => 0 0 & 0 => 0 | 5 =>00000101 12=>00001100 5&12 =>00000100=>4 |
| | Bitwise OR | 1 & 1 => 1 1 & 0 => 1 0 & 1 => 1 0 & 0 => 0 | 5 =>00000101 12=>00001100 5|12 =>00001101=>13 |
^ | Bitwise XOR | 1 & 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 Shift | 0111 << 2 => 11 | 12=>0000110012<<5 =>110000000=>384 |
>> | Right Shift | 0111 >> 2 => 01 | 140=>10001100140>>5 =>00000100=>4 |
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
=
(Assign) => Assigns the value on the right to the variable on the left+=
(Add and Assign) => Adds the right operand to the left operand and assigns the result to the left operand.-=
(Subtract and Assign) => Subtracts the right operand from the left operand and assigns the result to the left operand.*=
(Multiply and Assign) => Multiplies the left operand by the right operand and assigns the result to the left operand./=
(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.//=
(Floor Divide and Assign) => Floor divides the left operand by the right operand and assigns the result to the left operand.- %= (Modulus and Assign) => Modulus using the left operand and right operand and assigns the result to the left operand.
**=
(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
&=
(Bitwise AND and Assign) => Bitwise AND of the left operand with the right operand and assigns the result to the left operand.|=
(Bitwise OR and Assign) => Bitwise OR of the left operand with the right operand and assigns the result to the left operand.^=
(Bitwise XOR and Assign) => Bitwise XOR of the left operand with the right operand and assigns the result to the left operand.<<=
(Left Shift and Assign) => Left Shift of the left operand with the right operand and assigns the result to the left operand.>>=
(Right Shift and Assign) => Right Shift of the left operand with the right operand and assigns the result to the left operand.
Operator Name | Operator | Example |
---|---|---|
= | Assign | x = 20 |
+= | Add and Assign | x += 25 => x = x + 25 |
-= | Subtract and Assign | x -= 25 => x = x – 25 |
*= | Multiply and Assign | x *= 25 => x = x * 25 |
/= | Divide and Assign | x /= 25 => x = x / 25 |
//= | Floor Divide and Assign | x //= 25 => x = x // 25 |
%= | Modulus and Assign | x %= 25 => x = x % 25 |
**= | Exponent and Assign | x **= 25 => x = x ** 25 |
&= | Bitwise AND and Assign | x &= 25 => x = x & 25 |
|= | Bitwise OR and Assign | x |= 25 => x = x | 25 |
^= | Bitwise XOR and Assign | x ^= 25 => x = x ^ 25 |
<<= | Left Shift and Assign | x <<= 5 => x = x << 5 |
>>= | Right Shift and Assign | x >>= 5 => x = x >> 5 |
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.
is
=> Theis
operator returnsTrue
if the two operands refer to the same object (i.e., they have the same identity in memory).is not
=> Theis not
operator returnsTrue
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
andis 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.
in
=>in
operator returnsTrue
if specified value is present in the sequence. Otherwise, it returnsFalse
.not in
=>not in
operator returnsTrue
if specified value is not present in the sequence. Otherwise, it returnsFalse
.
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:
- Arithmetic Operators
- Comparison Operators
- Logical Operators
- Bitwise Operators
- Assignment Operators
- Identity Operators
- Membership Operators