Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manage empty list/invalid input when finding max/min value of list (Python)

I'm finding max value and min value of a list by using max(list) and min(list) in Python. However, I wonder how to manage empty lists.

For example if the list is an empty list [], the program raises 'ValueError: min() arg is an empty sequence' but I would like to know how to make the program just print 'empty list or invalid input' instead of just crashing. How to manage those errors?

like image 200
Jon_Computer Avatar asked Apr 13 '14 21:04

Jon_Computer


People also ask

Does empty list evaluate to false?

In Python, empty list object evaluates to false. Hence following conditional statement can be used to check if list is empty.

How do you find the max and min in Python?

Use Python's min() and max() to find smallest and largest values in your data. Call min() and max() with a single iterable or with any number of regular arguments. Use min() and max() with strings and dictionaries.

How does the min function work in Python?

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

What does MIN and MAX mean in Python?

max() function is used to find out the maximum value from the array elements or the elements of the particular array axis. min() function is used to find out the minimum value from the array elements or the particular array axis.


2 Answers

In Python 3.4, a default keyword argument has been added to the min and max functions. This allows a value of your choosing to be returned if the functions are used on an empty list (or another iterable object). For example:

>>> min([], default='no elements') 'no elements'  >>> max((), default=999) 999  >>> max([1, 7, 3], default=999) # 999 is not returned unless iterable is empty 7 

If the default keyword is not given, a ValueError is raised instead.

like image 162
Alex Riley Avatar answered Sep 21 '22 15:09

Alex Riley


Specifying a default in earlier versions of Python:

max(lst or [0]) max(lst or ['empty list']) 
like image 39
Curtis Yallop Avatar answered Sep 22 '22 15:09

Curtis Yallop