Use the operator module to represent standard operations as functions.
What You Will Learn
operator provides callable equivalents to common operators, along with efficient getter helpers. It is useful for map(), sorting keys, functional pipelines, and composable data processing.
Prefer a normal operator expression when it reads more clearly than a functional wrapper.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
from operator import add, itemgetter
print(add(8, 4))
people = [{'name': 'Ava', 'age': 30}, {'name': 'Leo', 'age': 24}]
print(sorted(people, key=itemgetter('age')))
How the Example Works
- The imports provide the standard-library tools used in the demonstration: operator.
- The variable people holds the result of [{'name': 'Ava', 'age': 30}, {'name': 'Leo', 'age': 24}]. Later lines use that value or inspect how it changes.
- The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.
Expected output from the example:
12
[{'name': 'Leo', 'age': 24}, {'name': 'Ava', 'age': 30}]
When You Would Use This
These tools are useful when composing small reusable functions, adapting callbacks, or eliminating repeated work. Pay attention to whether the operation returns a new object, updates state, or produces lazy results. Test a small success case and a boundary case before integrating it into an application.
Practice: Modify the Code
Replace a simple lambda sorting key with itemgetter().
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Assuming operator functions perform type conversion that their matching Python operators do not.
- Assuming the operation has the same behavior for missing values, empty inputs and regular inputs.
Key Takeaways
- Use the operator module to represent standard operations as functions.
- operator provides callable equivalents to common operators, along with efficient getter helpers.
- Prefer a normal operator expression when it reads more clearly than a functional wrapper.