A safe max() function for empty lists
In versions of Python older than 3.4 you can use itertools.chain()
to add another value to the possibly empty sequence. This will handle any empty iterable but note that it is not precisely the same as supplying the default
argument as the extra value is always included:
>>> from itertools import chain
>>> max(chain([42], []))
42
But in Python 3.4, the default is ignored if the sequence isn't empty:
>>> max([3], default=42)
3
In Python 3.4+, you can use default
keyword argument:
>>> max([], default=99)
99
In lower version, you can use or
:
>>> max([] or [99])
99
NOTE: The second approach does not work for all iterables. especially for iterator that yield nothing but considered truth value.
>>> max(iter([]) or 0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: max() arg is an empty sequence