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
Answer from falsetru on Stack OverflowIn 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
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
You've stumbled on to a difference in the implementation of .sort and max more than a problem with the language.
list.sort() takes a keyword argument "key" which happens to default to None. This means that the sort method can't tell the difference between you supplying a key=None argument or it just taking on the default value. In either case, it behaves as if no key function has been provided.
max on the other hand is checking for the presence of a keyword argument "key". It does not have a default value and it's value is used as the key function if present at all.
Either way, key should never be supplied as None. It is supposed to be a function which is used to extract a "key" value from the items in the list/iterable. For instance:
a = [("one", 1), ("two", 2), ("three", 3), ("four", 4)]
a.sort(key=lambda item:item[1])
@David's answer is perfect. Just adding, in case you're wondering, the default key value (both in sort and in max/min functions) is something like:
lambda x: x