I was writing up a blog article on what reduce
is, how it works, and the functions it hides behind, and at a certain point I talk about sum
, all
, any
, max
, and min
, all reductions.
Then, I talk about how reduce
accepts the third argument, the initial value, that should be the identity element of the function you are using.
Then, I proceed to show some specialised reductions have the identity element baked in:
>>> sum([])
0
>>> import math
>>> math.prod([])
1
>>> all([])
True
So, why is it that max
and min
throw errors when called with empty iterables,
when their operations have identity elements?
>>> max([])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: max() arg is an empty sequence
We can do float("-inf")
, so why isn't this the value returned by max([])
? Similarly, why doesn't min([])
return float("inf")
?