Engineering

Operators in Python

How different operators behave in different data structures

Shubham Negi
Building Fynd
Published in
13 min readMay 19, 2023

--

An operator in Python is a symbol that performs a unique operation on one or more operands. These are standard symbols used for the purpose of logical, arithmetic, identity, membership, and bitwise operations.

Types of Operators in Python

Python supports a variety of operators, including arithmetic, assignment, comparison, logical, identity, membership, and bitwise operators.

Let’s take a deeper look at each type of operator:

Arithmetic Operators:

Arithmetic operators are used to perform mathematical operations. The arithmetic operators include:

  • Addition (+): Adds two operands
  • Subtraction (-): Subtracts the second operand from the first
  • Multiplication (*): Multiplies two operands
  • Division (/): Divides the first operand by the second operand (returns a float)
  • Integer Division (//): Divides the first operand by the second operand and rounds down to the nearest integer
  • Modulus (%): Returns the remainder of the division of the first operand by the second operand
  • Exponentiation (**): Raises the first operand to the power of the second operand

Here’s an example:

a = 10
b = 3

print(a + b) # Output: 13
print(a - b) # Output: 7
print(a * b) # Output: 30
print(a / b) # Output: 3.3333333333333335
print(a // b) # Output: 3
print(a % b) # Output: 1
print(a ** b) # Output: 1000

Assignment Operator:

The assignment operator (=) is used to assign a value to a variable. The value on the right-hand side of the operator is assigned to the variable on the left-hand side.
Here’s an example:

a = 10
b = 5
c = a + b

print(c) # Output: 15

In the above example, the values of a and b are assigned using the assignment operator (=). The variable c is assigned the value of the sum of a and b, which is 15. Finally, the value c is printed on the console.

Python also provides compound assignment operators, which combine arithmetic and assignment operations into a single operator. These operators include:

  • Addition and Assignment (+=): Adds the value on the right-hand side to the variable on the left-hand side and assigns the result to the variable on the left-hand side.
  • Subtraction and Assignment (-=): Subtracts the value on the right-hand side from the variable on the left-hand side and assigns the result to the variable on the left-hand side.
  • Multiplication and Assignment (*=): Multiplies the value on the right-hand side by the variable on the left-hand side and assigns the result to the variable on the left-hand side.
  • Division and Assignment (/=): Divides the variable on the left-hand side by the value on the right-hand side and assigns the result to the variable on the left-hand side.
  • Modulus and Assignment (%=): Computes the remainder of the division of the variable on the left-hand side by the value on the right-hand side and assigns the result to the variable on the left-hand side.
  • Exponentiation and Assignment (**=): Raises the variable on the left-hand side to the power of the value on the right-hand side and assigns the result to the variable on the left-hand side.
  • Floor Division and Assignment (//=): Performs integer division on the variable on the left-hand side by the value on the right-hand side and assigns the result to the variable on the left-hand side.

Here’s an example:

a = 10
b = 5

a += b # equivalent to a = a + b
print(a) # Output: 15

a -= b # equivalent to a = a - b
print(a) # Output: 10

a *= b # equivalent to a = a * b
print(a) # Output: 50

a /= b # equivalent to a = a / b
print(a) # Output: 10.0

a %= b # equivalent to a = a % b
print(a) # Output: 0.0

a **= 2 # equivalent to a = a ** 2
print(a) # Output: 0.0

a //= 3 # equivalent to a = a // 3
print(a) # Output: 0.0

In the above example, the compound assignment operators are used to perform arithmetic operations on the values of a and b, and assign the results back to a. The result of each operation is printed on the console.

Note that you can also use the bitwise assignment operators to perform bitwise operations on the values of variables, and assign the results back to the variables. These operators include:

  • Bitwise AND and Assignment (&=)
  • Bitwise OR and Assignment (|=)
  • Bitwise XOR and Assignment (^=)
  • Bitwise Left Shift and Assignment (<<=)
  • Bitwise Right Shift and Assignment (>>=)

However, these operators are used less frequently.

Comparison Operators:

Comparison operators are used to compare two values. The comparison operators include:

  • Equal to (==): Returns True if the operands are equal
  • Not equal to (!=): Returns True if the operands are not equal
  • Greater than (>): Returns True if the first operand is greater than the second operand
  • Less than (<): Returns True if the first operand is less than the second operand
  • Greater than or equal to (>=): Returns True if the first operand is greater than or equal to the second operand
  • Less than or equal to (<=): Returns True if the first operand is less than or equal to the second operand

Here’s an example:

a = 10
b = 5
c = 10

print(a == b) # Output: False
print(a != b) # Output: True
print(a > b) # Output: True
print(a < b) # Output: False
print(a >= c) # Output: True
print(b <= c) # Output: True

In the above example, we have two variables a and b with different values, and a variable c with the same value as a. We use the comparison operators to compare the values of these variables and print the results to the console.
Note that the result of a comparison operator is always a boolean value (True or False).

Logical Operators:

Logical operators are used to combine conditional statements. The logical operators include:

  • and: Returns True if both operands are True.
  • or: Returns True if at least one of the operands is True.
  • not: Returns True if the operand is False.

Here’s an example:

a = 10
b = 3
c = 5

print(a > b and b < c) # Output: True
print(a < b or b > c) # Output: False
print(not(a > b)) # Output: False

Identity Operators:

Identity operators are used to compare the memory location of two objects. The identity operators include:

  • is: Returns True if both operands are the same object.
  • is not: Returns True if both operands are not the same object.

Here’s an example:

a = [1, 2, 3]
b = a
c = [1, 2, 3]

print(a is b) # Output: True
print(a is c) # Output: False
print(a is not c) # Output: True

Membership Operators:

Membership operators are used to test if a sequence is present in an object. In Python, membership operators include:

  • in: Returns True if a value is found in the sequence, otherwise False.
  • not in: Returns True if a value is not found in the sequence, otherwise False.

Here’s an example:

fruits = ["apple", "banana", "cherry"]

print("banana" in fruits) # Output: True
print("orange" in fruits) # Output: False
print("orange" not in fruits) # Output: True

In the above example, we have a list of fruits. We use the in and not in operators to check if certain values are present in the list. The first two lines check if "banana" and "orange" are in the list fruits, respectively. The last line checks if "orange" is not present in the list fruits.

Bitwise Operators:

Bitwise operators are used to perform operations on binary representations of integers. In Python, the bitwise operators are:

  • & (Bitwise AND): Returns 1 if both bits at the same position are 1, otherwise 0.
  • | (Bitwise OR): Returns 1 if either of the bits at the same position is 1, otherwise 0.
  • ^ (Bitwise XOR): Returns 1 if the bits at the same position are different, otherwise 0.
  • ~ (Bitwise NOT): Flips all the bits in a number. The resulting value is the two’s complement of the original value.
  • << (Bitwise Left Shift): Shifts the bits of the number to the left by the specified number of positions. The rightmost bits are filled with 0s.
  • >>(Bitwise Right Shift): Shifts the bits of the number to the right by the specified number of positions. The leftmost bits are filled with 0s.

Here’s an example that demonstrates the bitwise operators:

a = 60 # 60 = 0011 1100 in binary
b = 13 # 13 = 0000 1101 in binary

# Bitwise AND
c = a & b
print(c) # 12 = 0000 1100 in binary

# Bitwise OR
c = a | b
print(c) # 61 = 0011 1101 in binary

# Bitwise XOR
c = a ^ b
print(c) # 49 = 0011 0001 in binary

# Bitwise NOT
c = ~a
print(c) # -61 = 1100 0011 in binary (2's complement representation)

# Bitwise Left Shift
c = a << 2
print(c) # 240 = 1111 0000 in binary

# Bitwise Right Shift
c = a >> 2
print(c) # 15 = 0000 1111 in binary

In the example above, we first assign two integer values a and b. We then perform various bitwise operations on them using the corresponding bitwise operators.
Note that the bitwise NOT operator (~) flips all the bits in the number, including the sign bit, which results in the two's complement of the original number. The two's complement is the binary representation of the negative value of the original number.

Working with operators with different data structures

String:

1. Concatenation Operator (+): The plus sign (+) is used to concatenate or join two or more strings together.

# Example
greeting = "Hello, "
name = "John"
message = greeting + name

print(message) # Output: Hello, John

2. Repetition Operator (*): The asterisk (*) is used to repeat a string a certain number of times.

# Example
stars = "*"
row = stars * 5

print(row) # Output: *****

3. Membership Operators (in and not in): The in operator is used to check if a substring is present in a string. The not in operator is used to check if a substring is not present in a string.

# Example
my_string = "The quick brown fox jumps over the lazy dog"

print("quick" in my_string) # Output: True
print("slow" not in my_string) # Output: True

4. Comparison Operators (==, !=, <, >, <=, >=): These operators are used to compare two strings lexicographically.

# Example
string1 = "apple"
string2 = "banana"

print(string1 == string2) # Output: False
print(string1 < string2) # Output: True

List:

1. Assignment Operator (=): This operator is used to assign a value to a variable. For example:

my_list = [1, 2, 3, 4, 5]

2. Concatenation Operator (+): This operator is used to concatenate two or more lists. For example:

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = list1 + list2

print(list3) # Output: [1, 2, 3, 4, 5, 6]

3. Repetition Operator (*): This operator is used to repeat a list multiple times. For example:

list1 = [1, 2]
list2 = list1 * 3

print(list2) # Output: [1, 2, 1, 2, 1, 2]

4. Membership Operator (in): This operator is used to check if an element is present in a list or not. For example:

my_list = [1, 2, 3, 4, 5]

print(3 in my_list) # Output: True
print(6 in my_list) # Output: False

5. Membership Operator (not in): This operator is used to check if an element is present in a list or not. For example:

my_list = [1, 2, 3, 4, 5]

print(3 not in my_list) # Output: False
print(6 not in my_list) # Output: True

6. Identity Operator (is): This operator is used to check if two variables refer to the same object. For example:

list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1

print(list1 is list2) # Output: False
print(list1 is list3) # Output: True

7. Identity Operator (is not): This operator is used to check if two variables refer to the same object or not. For example:

list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1

print(list1 is not list2) # Output: True
print(list1 is not list3) # Output: False

8. Indexing Operator ([]): This operator is used to access a specific element in a list by its index. For example:

my_list = [1, 2, 3, 4, 5]
print(my_list[2]) # Output: 3

9. Slicing Operator ([start:stop:step]): This operator extracts a portion of a list. For example:

my_list = [1, 2, 3, 4, 5]

print(my_list[1:4]) # Output: [2, 3, 4]
print(my_list[:3]) # Output: [1, 2, 3]
print(my_list[::2]) # Output: [1, 3, 5]

Tuple:

1. Assignment Operator (=): The assignment operator is used to assign a value to a variable. For example, you can assign a tuple to a variable like this:

t = (1, 2, 3)

2. Addition Operator (+): The addition operator can be used to concatenate two tuples. For example:

t1 = (1, 2, 3)
t2 = (4, 5, 6)
t3 = t1 + t2

print(t3) # Output: (1, 2, 3, 4, 5, 6)

3. Multiplication Operator (*): The multiplication operator can be used to repeat a tuple a specified number of times. For example:

t = (1, 2, 3)
t2 = t * 2

print(t2) # Output: (1, 2, 3, 1, 2, 3)

4. Comparison Operators (==, !=, <, >, <=, >=): These operators are used to compare two tuples element-wise. For example:

t1 = (1, 2, 3)
t2 = (4, 5, 6)
t3 = (1, 2, 3)

print(t1 == t2) # Output: False
print(t1 == t3) # Output: True
print(t1 < t2) # Output: True
print(t2 > t3) # Output: True

5. Membership Operators (in, not in): These operators are used to check if an element is present in a tuple or not. For example:

t = (1, 2, 3)

print(1 in t) # Output: True
print(4 not in t) # Output: True

6. Identity Operators (is, is not): These operators are used to compare the identity of two tuples. For example:

t1 = (1, 2, 3)
t2 = (1, 2, 3)
t3 = t1

print(t1 is t2) # Output: False
print(t1 is t3) # Output: True
print(t1 is not t2) # Output: True

7. Slice Operator (:): The slice operator is used to extract a range of elements from a tuple. For example:

t = (1, 2, 3, 4, 5)
print(t[1:3]) # Output: (2, 3)

8. Index Operator ([]): The index operator is used to access a specific element of a tuple. For example:

t = (1, 2, 3)
print(t[0]) # Output: 1

Set:

1. Union operator (|): The union operator combines two sets and returns a new set containing all unique elements from both sets.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
set3 = set1 | set2

print(set3) # Output: {1, 2, 3, 4, 5}

2. Intersection operator (&): The intersection operator returns a new set containing common elements between two sets.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
set3 = set1 & set2

print(set3) # Output: {3}

3. Difference operator (-): The difference operator returns a new set containing elements from the first set that are not present in the second set.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
set3 = set1 - set2

print(set3) # Output: {1, 2}

4. Symmetric difference operator (^): The symmetric difference operator returns a new set containing elements that are in either of the sets, but not in both.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
set3 = set1 ^ set2

print(set3) # Output: {1, 2, 4, 5}

5. Subset operator (<): The subset operator checks if one set is a subset of another set and returns a boolean value.

set1 = {1, 2, 3}
set2 = {1, 2}

print(set2 < set1) # Output: True

6. Superset operator (>): The superset operator checks if one set is a superset of another set and returns a boolean value.

set1 = {1, 2, 3}
set2 = {1, 2}

print(set1 > set2) # Output: True

7. Set Membership operator (in): The membership operator checks if a particular element is present in a set and returns a boolean value.

set1 = {1, 2, 3}
print(2 in set1) # Output: True

8. Set Non-membership operator (not in): The non-membership operator checks if a particular element is not present in a set and returns a boolean value.

set1 = {1, 2, 3}
print(4 not in set1) # Output: True

9. Set Identity operator (is): The identity operator checks if two sets are the same object and returns a boolean value.

set1 = {1, 2, 3}
set2 = {1, 2, 3}
print(set1 is set2) # Output: False

10. Set Non-Identity operator (is not): The non-identity operator checks if two sets are not the same object and returns a boolean value.

set1 = {1, 2, 3}
set2 = {1, 2, 3}
print(set1 is not set2) # Output: True

Dictionary:

1. Assignment Operator (=): This operator is used to assign values to a dictionary. For example:

dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

2. Accessing Operator ([]): This operator is used to access the value of a specific key in the dictionary. For example:

dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
print(dict['key2']) #Output: 'value2'

3. in operator: This operator is used to check if a key is present in the dictionary.

my_dict = {'apple': 3, 'banana': 2, 'orange': 5}

# Check if 'apple' is a key in the dictionary
if 'apple' in my_dict:
print("Yes, 'apple' is a key in the dictionary")
# Check if 'mango' is a key in the dictionary
if 'mango' in my_dict:
print("Yes, 'mango' is a key in the dictionary")
else:
print("No, 'mango' is not a key in the dictionary")

4. not in operator: This operator is used to check if a key is not present in the dictionary.

my_dict = {'apple': 3, 'banana': 2, 'orange': 5}

# Check if 'apple' is not a key in the dictionary
if 'apple' not in my_dict:
print("No, 'apple' is not a key in the dictionary")
else:
print("Yes, 'apple' is a key in the dictionary")
# Check if 'mango' is not a key in the dictionary
if 'mango' not in my_dict:
print("Yes, 'mango' is not a key in the dictionary")

5. | operator: This operator can be used to perform the union operation on two dictionaries. The union operation on dictionaries combines the key-value pairs of two dictionaries into a single dictionary.

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}

# perform union on dict1 and dict2 using |
result = dict1 | dict2
print(result) # Output: {'a': 1, 'b': 3, 'c': 4}

Conclusion

In this blog, we have covered all the operators with example programs to demonstrate their usefulness in Python programming. Each operator is unique and performs a separate set of functions, contributing to Python’s success as a programming language. Use this guide to explore examples showcasing the usage of each operator and expand your knowledge. Happy reading!

Thank you to Manoj Baghela and Kedar Aitawdekar for their guidance and support!

--

--