# 6.14. Operator Module¶

• operator.add()

• operator.sub()

• operator.mul()

• operator.truediv()

• operator.floordiv()

• operator.mod()

• operator.pow()

• operator.matmul()

• operator.neg()

• operator.pos()

• operator.invert()

## 6.14.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


## 6.14.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


## 6.14.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


## 6.14.4. Reduce¶

>>> from functools import reduce
>>>
>>> data = [1, 2, 3, 4]

>>> def add(x, y):
...     return x + y
>>>
>>> def sub(x, y):
...     return x - y
>>>
>>> def mul(x, y):
...     return x * y
>>>
>>>
10
>>> reduce(sub, data)
-8
>>> reduce(mul, data)
24

>>> reduce(lambda x,y: x+y, data)
10
>>> reduce(lambda x,y: x-y, data)
-8
>>> reduce(lambda x,y: x*y, data)
24

>>> from operator import add, sub, mul
>>>
10
>>> reduce(sub, data)
-8
>>> reduce(mul, data)
24


## 6.14.5. 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']


## 6.14.6. Reduce¶

>>> from functools import reduce

>>> data = [
...     [1, 2, 3],
...     [4, 5, 6],
...     [7, 8, 9],
... ]

>>> result = 0
>>>
>>> for row in data:
...     for digit in row:
...         result += digit
>>>
>>> print(result)
45

>>> sum(data[0])
6
>>>
>>> sum(data[1])
15
>>>
>>> sum(data[2])
24
>>>
>>>
>>> sum(data[0]) + sum(data[1]) + sum(data[2])
45

>>> reduce(add, data[0])
6
>>>
15
>>>
24
>>>
>>>
... ])
45


## 6.14.7. Map-Reduce¶

>>> from functools import reduce
>>> from itertools import starmap
>>> from operator import add, sub, mul

>>> def square(x):
...     return x ** 2
>>>
>>> def cube(x):
...     return x ** 3
>>>
>>> def apply(data, fn):
...     return map(fn, data)

>>> data = [1, 2, 3, 4]
>>> funcs = [square, cube]
>>>
>>> result = reduce(apply, funcs, data)
>>> list(result)
[1, 64, 729, 4096]
>>>
>>> result = reduce(apply, funcs, data)
4890

>>> data = [1, 2, 3, 4]
>>> funcs = [add, sub, mul]
>>>
>>> result = [reduce(fn,data) for fn in funcs]
26
>>>
>>> result = map(lambda fn: reduce(fn,data), funcs)
26

>>> data = [1, 2, 3, 4]
>>> funcs = [
...     (sub, data),
...     (mul, data),
... ]
>>>
>>> result = starmap(reduce, funcs)

>>> data = [1, 2, 3, 4]