Skip to content

Python Operator Module

  • by

In Python, the operator module is a built-in module that provides a set of functions corresponding to the standard Python operators.

It is often used to perform operations on various data structures, such as lists, tuples, dictionaries, and custom objects, in a concise and efficient manner. Using the operator module can result in more readable code and can be especially helpful when working with functional programming techniques or performing complex operations.

The operator module includes functions for a wide range of operations, such as arithmetic operations, comparison operations, logical operations, item access operations, and more. Here are some commonly used functions from the operator module:

Arithmetic Operations:

OperationFunctionExampleOutput (Example)
Additionoperator.add(a, b)operator.add(2, 3)5
Subtractionoperator.sub(a, b)operator.sub(7, 4)3
Multiplicationoperator.mul(a, b)operator.mul(2, 6)12
True Divisionoperator.truediv(a, b)operator.truediv(7, 2)3.5
Floor Divisionoperator.floordiv(a, b)operator.floordiv(7, 2)3
Modulooperator.mod(a, b)operator.mod(7, 3)1

Comparison Operations:

Equaloperator.eq(a, b)operator.eq(5, 5)True
Not Equaloperator.ne(a, b)operator.ne(2, 3)True
Less Thanoperator.lt(a, b)operator.lt(4, 9)True
Less Than or Equal Tooperator.le(a, b)operator.le(3, 3)True
Greater Thanoperator.gt(a, b)operator.gt(7, 5)True

Logical Operations:

Logical OperationFunctionExampleOutput (Example)
Bitwise ANDoperator.and_(a, b)operator.and_(5, 3)1
Bitwise ORoperator.or_(a, b)operator.or_(5, 3)7
Bitwise XORoperator.xor(a, b)operator.xor(5, 3)6
Bitwise NOToperator.not_(a)operator.not_(5)-6

Item Access Operations:

Item Access OperationFunctionExampleOutput (Example)
Get Item (Indexing)operator.getitem(sequence, index)operator.getitem([1, 2, 3], 1)2
Set Item (Indexing)operator.setitem(sequence, index, value)operator.setitem([1, 2, 3], 1, 9)[1, 9, 3]
Delete Item (Indexing)operator.delitem(sequence, index)operator.delitem([1, 2, 3], 1)[1, 3]

The operator module is often used in combination with higher-order functions like map(), filter(), and functools.reduce() to achieve concise and efficient code for common operations.

Python Operator Module example

Here’s an example of using the operator module to perform some operations on lists:

import operator

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

# add 10 to each element in the list
result = list(map(operator.add, numbers, [10] * len(numbers)))
print(result)

# Reduce to calculate the product of all elements in the list
import functools
product = functools.reduce(operator.mul, numbers)
print(product)

# sort a list of tuples based on the second element
data = [(1, 5), (2, 2), (3, 9), (4, 3)]
sorted_data = sorted(data, key=operator.itemgetter(1))
print(sorted_data)

Output:

Python Operator Module

Let’s see an example of how to use the operator module in Python to perform some common operations:

import operator

# Arithmetic Operations
result_add = operator.add(5, 3)       # 5 + 3 = 8
result_sub = operator.sub(10, 4)      # 10 - 4 = 6
result_mul = operator.mul(2, 5)       # 2 * 5 = 10
result_truediv = operator.truediv(7, 2)  # 7 / 2 = 3.5
result_floordiv = operator.floordiv(7, 2) # 7 // 2 = 3
result_mod = operator.mod(7, 3)       # 7 % 3 = 1
result_pow = operator.pow(2, 3)       # 2 ** 3 = 8

# Comparison Operations
result_eq = operator.eq(5, 5)        # 5 == 5 -> True
result_ne = operator.ne(2, 3)        # 2 != 3 -> True
result_lt = operator.lt(4, 9)        # 4 < 9 -> True
result_le = operator.le(3, 3)        # 3 <= 3 -> True
result_gt = operator.gt(7, 5)        # 7 > 5 -> True
result_ge = operator.ge(5, 5)        # 5 >= 5 -> True

# Logical Operations
result_and = operator.and_(5, 3)     # 0101 & 0011 -> 0001 (1 in decimal)
result_or = operator.or_(5, 3)       # 0101 | 0011 -> 0111 (7 in decimal)
result_xor = operator.xor(5, 3)      # 0101 ^ 0011 -> 0110 (6 in decimal)
result_not = operator.not_(5)        # ~0101 -> -6 (bitwise NOT)

# Item Access Operations
numbers = [1, 2, 3, 4, 5]
get_item_result = operator.getitem(numbers, 2)  # Get the item at index 2 -> 3
set_item_result = operator.setitem(numbers, 2, 9)  # Set the item at index 2 to 9 -> numbers is now [1, 2, 9, 4, 5]
del_item_result = operator.delitem(numbers, 3)  # Delete the item at index 3 -> numbers is now [1, 2, 9, 5]

print("Arithmetic Operations:")
print("Addition:", result_add)
print("Subtraction:", result_sub)
print("Multiplication:", result_mul)
print("True Division:", result_truediv)
print("Floor Division:", result_floordiv)
print("Modulo:", result_mod)
print("Exponentiation:", result_pow)

print("\nComparison Operations:")
print("Equal:", result_eq)
print("Not Equal:", result_ne)
print("Less Than:", result_lt)
print("Less Than or Equal To:", result_le)
print("Greater Than:", result_gt)
print("Greater Than or Equal To:", result_ge)

print("\nLogical Operations:")
print("Bitwise AND:", result_and)
print("Bitwise OR:", result_or)
print("Bitwise XOR:", result_xor)
print("Bitwise NOT:", result_not)

print("\nItem Access Operations:")
print("Get Item (Indexing):", get_item_result)
print("Set Item (Indexing):", numbers)
print("Delete Item (Indexing):", numbers)

In this example, we use various functions from the operator module to perform arithmetic operations, comparison operations, logical operations, and item access operations on different data types. The results are then printed to the console.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading