2 min read

Python Operator Module

The operator module exports a set of efficient functions corresponding to the intrinsic operators of Python. For example, operator.add(x, y) is equivalent to the expression x + y.

Importing the Module

import operator

Arithmetic Operators

The module provides functions for standard arithmetic operations.

  • operator.add(a, b): a + b
  • operator.sub(a, b): a - b
  • operator.mul(a, b): a * b
  • operator.truediv(a, b): a / b
  • operator.floordiv(a, b): a // b
  • operator.mod(a, b): a % b
  • operator.pow(a, b): a ** b
import operator

a = 10
b = 3

print(operator.add(a, b))      # Output: 13
print(operator.floordiv(a, b)) # Output: 3

Comparison Operators

  • operator.lt(a, b): a < b
  • operator.le(a, b): a <= b
  • operator.eq(a, b): a == b
  • operator.ne(a, b): a != b
  • operator.ge(a, b): a >= b
  • operator.gt(a, b): a > b
import operator

x = 5
y = 10

print(operator.lt(x, y)) # Output: True

Higher-Order Functions

The operator module provides tools for functional programming, often used with map(), sorted(), itertools.groupby(), etc.

itemgetter

Return a callable object that fetches item from its operand using the operand’s __getitem__() method.

import operator

data = [('apple', 3), ('banana', 2), ('pear', 5)]

# Sort by the second element (count)
data.sort(key=operator.itemgetter(1))
print(data)
# Output: [('banana', 2), ('apple', 3), ('pear', 5)]

attrgetter

Return a callable object that fetches attribute from its operand.

import operator

class User:
    def __init__(self, name, id):
        self.name = name
        self.id = id
    def __repr__(self):
        return f"User({self.name})"

users = [User('Alice', 2), User('Bob', 1)]

# Sort by id
users.sort(key=operator.attrgetter('id'))
print(users)
# Output: [User(Bob), User(Alice)]

methodcaller

Return a callable object that calls the method name on its operand.

import operator

s = "hello world"
up = operator.methodcaller('upper')
print(up(s)) # Output: HELLO WORLD

programming/python/python