The operator Module
Published by Brayan K
The operator module turns Python's operators and lookups into plain, reusable functions, so you can pass things like "add", "get item 1", or "call .upper()" anywhere a function is expected.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
An operator function is a callable you can pass around
Sometimes an API needs a function rather than an expression. operator.add gives you the behavior of addition as a callable, and operator.mul does the same for multiplication. The benefit is making the operation a value you can pass or select, not making every ordinary expression shorter.
from operator import add, mul
operations = {"add": add, "multiply": mul}
operation = operations["multiply"]
print(operation(6, 7))
print(add("code", " review"))
print(add([1], [2]))
# ✅ Expected output:
# 42
# code review
# [1, 2]The operand types still determine the meaning. add can concatenate strings or lists because the corresponding plus expressions do so. It is not a numeric-only validator. Operator Overloading & Custom Behaviours owns custom operator behavior; this module exposes those operations through ordinary functions.
A small dispatch dictionary makes the allowed operations visible. Validate the requested name and arguments before calling the selected function. Do not replace the dictionary with eval on user-supplied text.
itemgetter builds a reader; it does not read immediately
from operator import itemgetter
score = itemgetter("score")
records = [{"name": "Ada", "score": 8}, {"name": "Lin", "score": 12}]
print([score(record) for record in records])
records[0]["score"] = 10
print(score(records[0]))
# ✅ Expected output:
# [8, 12]
# 10The factory stores the key, not a snapshot of the record. Each call performs indexing on the object supplied then. itemgetter("score") works for dictionaries supporting that key; itemgetter(1) works for sequences supporting that position. These are the same indexing contracts, including their failures.
from operator import itemgetter
row = ("Ada", 8, "blue")
print(itemgetter(2, 0)(row))
print(itemgetter(slice(0, 2))(row))
print(itemgetter("a.b")({"a.b": 7}))
# ✅ Expected output:
# ('blue', 'Ada')
# ('Ada', 8)
# 7With several keys, itemgetter returns a tuple of selected values. One slice is still one indexing operation and returns whatever slicing that object normally returns. A dot inside a dictionary key is literal; itemgetter does not treat it as a nested lookup path.
from operator import itemgetter
itemgetter("score")({"name": "Ada"})
# ✅ Expected error:
# KeyError: 'score'Use an explicitly written function with record.get when a fallback is part of the contract. A factory is helpful only when its behavior matches the task. Lambda Functions owns small custom function expressions, and Higher-Order Functions & Function Factories owns building your own factories.
attrgetter follows attributes, including dotted attribute paths
from operator import attrgetter
from types import SimpleNamespace
person = SimpleNamespace(name="Ada", team=SimpleNamespace(code="blue"))
read = attrgetter("name", "team.code")
print(read(person))
# ✅ Expected output:
# ('Ada', 'blue')from operator import attrgetter
attrgetter("score")({"score": 8})
# ✅ Expected error:
# AttributeError: 'dict' object has no attribute 'score'attrgetter uses getattr semantics. The dotted path follows successive attributes; it does not switch to dictionary indexing halfway through. Missing attributes raise AttributeError. Decide whether your data is represented by mappings or objects before choosing a getter.
from operator import attrgetter
events = []
class Record:
@property
def score(self):
events.append("read")
return 8
record = Record()
read = attrgetter("score")
print(events)
print(read(record))
print(events)
# ✅ Expected output:
# []
# 8
# ['read']Creating the getter did not evaluate the property; applying it did. A getter is not a side-effect-free snapshot mechanism. Properties & Descriptors owns attribute descriptor behavior, and Introspection with inspect covers inspecting attributes without invoking ordinary lookup in cases that need it.
methodcaller looks up and calls a method on each supplied object
from operator import methodcaller
normalize = methodcaller("strip")
replace_separator = methodcaller("replace", "-", " ")
print(normalize(" ready "))
print(replace_separator("code-review"))
append_note = methodcaller("append", "checked")
notes = []
print(append_note(notes))
print(notes)
# ✅ Expected output:
# ready
# code review
# None
# ['checked']methodcaller does not hold a bound method from a particular object. It looks up the named method on the object passed to the resulting callable. Its stored arguments are passed to that method. The return value is the method’s return value: list.append mutates the list and returns None.
Use itemgetter for indexing, attrgetter for attributes and methodcaller when you intend a method call. Naming that distinction helps a reader understand the operation without reverse-engineering a dense chain of lambdas.
In-place operations can preserve or replace identity
from operator import iadd
items = [1]
alias = items
result = iadd(items, [2])
print(items)
print(result is alias)
values = (1,)
alias = values
result = iadd(values, (2,))
print(values)
print(result)
print(result is alias)
# ✅ Expected output:
# [1, 2]
# True
# (1,)
# (1, 2)
# FalseFor the list, in-place addition mutates the existing object. For the tuple, it produces another tuple. iadd performs the operation but does not rebind your variable for you. Assign the returned value when you need behavior corresponding to an augmented assignment whose result may be a different object.
“In-place” does not mean the same identity is guaranteed for every operand type. The object’s operation decides whether it can mutate or must return a replacement. Aliases make the difference observable.
Callable operators do not reproduce short-circuit syntax
from operator import and_
events = []
def left():
events.append("left")
return False
def right():
events.append("right")
return True
print(and_(left(), right()))
print(events)
events.clear()
print(left() and right())
print(events)
# ✅ Expected output:
# False
# ['left', 'right']
# False
# ['left']and_ implements bitwise ampersand behavior; it is not the language’s short-circuit and expression. Function arguments are evaluated before the call, so both helpers run. The same warning applies to or_ versus or. Use the language syntax when later evaluation must depend on the earlier result.
from operator import index
print(index(3))
index(3.5)
# ✅ Expected output:
# 3
# ✅ Expected error:
# TypeError: 'float' object cannot be interpreted as an integerindex asks for an exact integer index through the integer-index protocol. It does not perform the lossy conversion that int can perform on a float. This distinction matters for APIs that need a real count or position rather than a rounded interpretation.
Complete a reusable key selector
Build a getter for the score key and pass the callable itself to sorted. Do not call it without a record. The sorting rules belong to Sorting with sorted() & key.
from operator import itemgetter
records = [{"name": "Lin", "score": 12}, {"name": "Ada", "score": 8}]
key = itemgetter(___)
ordered = sorted(records, key=___)
print([record["name"] for record in ordered])
# 👉 replace ___ with "score"
# 👉 replace ___ with key
# ✅ Expected output:
# ['Ada', 'Lin']Calculate a small report from explicit record fields
Each tuple contains a name, a unit count and points per unit. Use itemgetter to retrieve the two numeric fields and operator.mul to calculate each total. Produce dictionaries with name and total, sort them by name using a getter, and print the ordered report. The records are Ada with 3 units at 4 points and Lin with 2 units at 9 points.
from operator import itemgetter, mul
rows = [("Lin", 2, 9), ("Ada", 3, 4)]
quantities = itemgetter(1, 2)
reports = []
for row in rows:
units, points = quantities(row)
reports.append({"name": row[0], "total": mul(units, points)})
ordered = sorted(reports, key=itemgetter("name"))
print([(record["name"], record["total"]) for record in ordered])
# ✅ Expected output:
# [('Ada', 12), ('Lin', 18)]
Practice quiz
What does this program print? from operator import itemgetter print(itemgetter(2, 0)(["A", "B", "C"]))
- ('C', 'A')
- ['C', 'A']
- ('A', 'C')
- {'C': 'A'}
Answer: ('C', 'A'). Multiple requested items produce a tuple in request order.
What does this program print? from operator import itemgetter read = itemgetter("a.b") print(read({"a.b": 7}))
- AttributeError
- 7
- KeyError
- ("a", "b")
Answer: 7. itemgetter treats the dotted text as a literal key.
Which callable invokes a property when applied to its object?
- itemgetter on a dictionary
- A stored plain string
- attrgetter for that property name
- A set of attribute names
Answer: attrgetter for that property name. attrgetter uses ordinary attribute lookup, which can execute descriptors.
What does this program print? from operator import methodcaller items = [] print(methodcaller("append", 4)(items)) print(items)
- [4] [4]
- 4 []
- None []
- None [4]
Answer: None [4]. methodcaller returns append’s None while the receiver is mutated.
What does this program print? from operator import iadd values = (1,) result = iadd(values, (2,)) print(values) print(result)
- (1,) (1, 2)
- (1, 2) (1, 2)
- (1,) (2,)
- None (1, 2)
Answer: (1,) (1, 2). The immutable tuple is replaced in the returned result; the original variable is not rebound.
Why can operator.and_(first(), second()) call second when first returns False?
- Because False is truthy
- Because ordinary function arguments are evaluated eagerly
- Because and_ retries failed functions
- Because operator ignores the first argument
Answer: Because ordinary function arguments are evaluated eagerly. and_ is a bitwise callable, not short-circuit and syntax.
What does this program print? from operator import add print(add("ab", "cd"))
- TypeError
- ["ab", "cd"]
- abcd
- 4
Answer: abcd. Operator functions retain the operand types’ normal behavior.
What does itemgetter("missing") do when applied to a dictionary without that key?
- Returns None
- Creates the key
- Returns a default empty string
- Raises KeyError
Answer: Raises KeyError. It uses normal indexing and has no default-value parameter.
Continue this course
- Previous: The statistics Module
- Next: Binary Data with struct — Pack and unpack C-style binary data and read file headers
- Quick reference: Python cheat sheet