8.12. Operator Stdlib

  • operator.add()

  • operator.sub()

  • operator.mul()

  • operator.truediv()

  • operator.floordiv()

  • operator.mod()

  • operator.pow()

  • operator.matmul()

  • operator.neg()

  • operator.pos()

  • operator.invert()

The operator module in Python provides a set of functions that correspond to the built-in operators in Python. These functions can be used to perform operations on data types such as numbers, strings, and lists.

The module contains functions for arithmetic operations such as addition, subtraction, multiplication, and division, as well as functions for logical operations such as AND, OR, NOT, and XOR. It also includes functions for comparison operations such as less than, greater than, equal to, and not equal to.

One of the main benefits of using the operator module is that it allows you to perform operations on objects that may not support the corresponding operator. For example, you can use the operator.add() function to add two lists together, even though the + operator is not supported for lists.

Overall, the operator module provides a convenient way to perform operations in Python and can be particularly useful in functional programming.

8.12.1. Operator Module - AND

1 & 1 = 1
1 & 0 = 0
0 & 1 = 0
0 & 0 = 0
>>> from operator import and_
>>>
>>>
>>> and_(True, True)
True
>>> and_(True, False)
False
>>> and_(False, True)
False
>>> and_(False, False)
False

8.12.2. Operator Module - OR

1 | 1 = 1
1 | 0 = 1
0 | 1 = 1
0 | 0 = 0
>>> from operator import or_
>>>
>>>
>>> or_(True, True)
True
>>> or_(True, False)
True
>>> or_(False, True)
True
>>> or_(False, False)
False

8.12.3. Operator Module - XOR

1 ^ 1 = 0
1 ^ 0 = 1
0 ^ 1 = 1
0 ^ 0 = 0
>>> from operator import xor
>>>
>>>
>>> xor(True, True)
False
>>> xor(True, False)
True
>>> xor(False, True)
True
>>> xor(False, False)
False

8.12.4. Methodcaller

>>> from operator import methodcaller
>>>
>>> colors = ['red', 'green', 'blue']
>>> result = filter(lambda x: x.startswith('r'), colors)
>>> list(result)
['red']
>>> result = filter(methodcaller('startswith', 'r'), colors)
>>> list(result)
['red']