operator | Python Standard Library – Real Python
The Python operator module provides functions that correspond to the Python operators. This module allows you to use operators as functions, which can be especially useful when combined with higher-order functions, such as map(), filter(), and reduce().
Here’s a quick example:
Key Features
- Provides function equivalents for standard Python operators
- Supports Boolean, mathematical, comparison, identity, membership, and bitwise operations
- Offers item and attribute getter functions for convenience
Frequently Used Classes and Functions
Examples
Using the operator.sub() function:
Using operator.itemgetter() to extract elements by index:
Common Use Cases
- Replacing
lambdafunctions with more readable operator functions - Using
itemgetter()andattrgetter()for sorting and key extraction - Performing functional programming operations in a concise manner
Real-World Example
Suppose you have a list of tuples representing students’ grades, and you want to sort them by their scores:
In this example, you use operator.itemgetter() to sort a list of tuples by the second element, providing a clear and efficient solution.
For additional information on related topics, take a look at the following resources:
- Operators and Expressions in Python (Tutorial)
- Functional Programming in Python: When and How to Use It (Tutorial)
- Python's map(): Processing Iterables Without a Loop (Tutorial)
- Python's filter(): Extract Values From Iterables (Tutorial)
- Python's reduce(): From Functional to Pythonic Style (Tutorial)
- How to Use Python Lambda Functions (Tutorial)
- Python Operators and Expressions (Course)
- Python Operators and Expressions (Quiz)
- Using Functional Programming in Python (Course)
- Functional Programming in Python: When and How to Use It (Quiz)
- Python's map() Function: Transforming Iterables (Course)
- Filtering Iterables With Python (Course)
- Using Python Lambda Functions (Course)
- Python Lambda Functions (Quiz)