Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A safe max() function for empty lists

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  
like image 443
Alexander McFarlane Avatar asked Mar 22 '16 15:03

Alexander McFarlane


People also ask

Can we use MAX function in list?

The max() Function — Find the Largest Element of a List. In Python, there is a built-in function max() you can use to find the largest number in a list. To use it, call the max() on a list of numbers. It then returns the greatest number in that list.

Can we use MAX function in list in Python?

The Python max() function returns the largest value in an iterable, such as a list. If a list contains strings, the last item alphabetically is returned by max().

How does Max function work in Python?

The max() function returns the item with the highest value, or the item with the highest value in an iterable. If the values are strings, an alphabetically comparison is done.

How do you find the maximum value of a list?

Method: Use the max() and def functions to find the largest element in a given list. The max() function prints the largest element in the list.


2 Answers

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 
like image 79
falsetru Avatar answered Sep 30 '22 21:09

falsetru


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 
like image 40
Duncan Avatar answered Sep 30 '22 21:09

Duncan