The operator
module in Python provides a set of efficient functions that correspond to standard operators. It allows you to use functions as arguments to higher-order functions and helps in writing more functional-style code.
1. Common Functions in the operator
Module
1.1. Arithmetic Operators
import operator
# Addition
print(operator.add(2, 3)) # Output: 5
# Subtraction
print(operator.sub(5, 3)) # Output: 2
# Multiplication
print(operator.mul(4, 3)) # Output: 12
# Division
print(operator.truediv(10, 2)) # Output: 5.0
# Floor Division
print(operator.floordiv(10, 3)) # Output: 3
# Modulus
print(operator.mod(10, 3)) # Output: 1
# Power
print(operator.pow(2, 3)) # Output: 8
1.2. Comparison Operators
import operator
# Equal to
print(operator.eq(4, 4)) # Output: True
# Not equal to
print(operator.ne(4, 5)) # Output: True
# Greater than
print(operator.gt(5, 3)) # Output: True
# Less than
print(operator.lt(3, 5)) # Output: True
# Greater than or equal to
print(operator.ge(5, 5)) # Output: True
# Less than or equal to
print(operator.le(3, 5)) # Output: True
1.3. Logical Operators
import operator
# Logical AND
print(operator.and_(True, False)) # Output: False
# Logical OR
print(operator.or_(True, False)) # Output: True
# Logical NOT
print(operator.not_(True)) # Output: False
1.4. Item and Attribute Operations
import operator
# Get item from a list
my_list = [1, 2, 3]
print(operator.getitem(my_list, 1)) # Output: 2
# Set item in a list
operator.setitem(my_list, 1, 10)
print(my_list) # Output: [1, 10, 3]
# Delete item from a list
operator.delitem(my_list, 1)
print(my_list) # Output: [1, 3]
1.5. Functions for Callable Objects
import operator
# Check if an object is callable
print(operator.callable(len)) # Output: True
print(operator.callable(42)) # Output: False
2. Using operator
with Functional Programming
The operator
module is often used with functional programming tools such as map()
, filter()
, and reduce()
:
from functools import reduce
import operator
# List of numbers
numbers = [1, 2, 3, 4, 5]
# Compute the product of all numbers using reduce and operator.mul
result = reduce(operator.mul, numbers)
print(result) # Output: 120
3. Conclusion
The operator
module provides a range of efficient, functional-style operations for standard operators, comparisons, and more. It is useful for writing concise and functional code, especially when working with functions as first-class objects.