Junior
What is the purpose of the operator module in Python?
sobes.tech AI
Answer from AI
The operator module provides a set of functions corresponding to Python's built-in operators. This allows using operators as functions, which is useful in functional programming, e.g., with map(), filter(), and reduce(), as well as for key in sorting functions.
Main categories:
- Comparison:
lt,le,eq,ne,ge,gt. - Logical:
not_,and_,or_,xor. - Mathematical:
add,sub,mul,truediv,floordiv,mod,pow,neg,pos,abs. - Bitwise:
lshift,rshift,invert. - In-place:
iadd,isub,imul, etc. - Item/getter:
itemgetter,attrgetter,methodcaller.
# Example usage of operator.add with map
import operator
def apply_operation(data, operation, value):
# Apply operation to each element in data
return list(map(operation, data, [value] * len(data)))
numbers = [1, 2, 3, 4, 5]
# Add 10 to each number using operator.add
result = apply_operation(numbers, operator.add, 10)
# result will be [11, 12, 13, 14, 15]
# Using operator.itemgetter with sorted
data = [('apple', 3), ('banana', 1), ('cherry', 2)]
# Sort by second element
sorted_data = sorted(data, key=operator.itemgetter(1))
# sorted_data will be [('banana', 1), ('cherry', 2), ('apple', 3)]