Evaluating,
max_val = max(a)
will cause the error,
ValueError: max() arg is an empty sequence
Is there a better way of safeguarding against this error other than a try
, except
catch?
a = []
try:
max_val = max(a)
except ValueError:
max_val = default
Another solution could be by using ternary operators:
or
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 thedefault
argument as the extra value is always included:But in Python 3.4, the default is ignored if the sequence isn't empty:
In Python 3.4+, you can use
default
keyword argument:In lower version, you can use
or
:NOTE: The second approach does not work for all iterables. especially for iterator that yield nothing but considered truth value.
The max of an empty sequence "should" be an infinitely small thing of whatever type the elements of the sequence have. Unfortunately, (1) with an empty sequence you can't tell what type the elements were meant to have and (2) there is, e.g., no such thing as the most-negative integer in Python.
So you need to help
max
out if you want it to do something sensible in this case. In recent versions of Python there is adefault
argument tomax
(which seems to me a misleading name, but never mind) which will be used if you pass in an empty sequence. In older versions you will just have to make sure the sequence you pass in isn't empty -- e.g., byor
ing it with a singleton sequence containing the value you'd like to use in that case.[EDITED long after posting because Yaakov Belch kindly pointed out in comments that I'd written "infinitely large" where I should have written "infinitely small".]
Considering all the comments above it can be a wrapper like this:
Can create simple lambda to do this:
You can call it this way:
get_max(your_list)