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

3

46

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?

Despite answered 13/4, 2014 at 21:59 Comment(0)
R
16

Catch and handle the exception.

try:
    print(min(l), max(l))
except (ValueError, TypeError):
    print('empty list or invalid input')

ValueError is raised with an empty sequence. TypeError is raised when the sequence contains unorderable types.

Remember answered 13/4, 2014 at 22:3 Comment(2)
this is prefered way to do this in python (exceptions are cheap): docs.python.org/3/glossary.html#term-eafpDinsmore
There's a side-effect: if some other error occurs lower on the stack that happens to be of the same type, it'll be caught too. This inaccuracy is the primary source of critique for exception handling. In this particular case, this is probably of little concern though.Causeuse
S
101

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.

Stalactite answered 3/1, 2015 at 17:16 Comment(0)
T
52

Specifying a default in earlier versions of Python:

max(lst or [0])
max(lst or ['empty list'])
Touchdown answered 15/7, 2015 at 18:10 Comment(2)
Very nice. For the curious, this works because empty lists are falsy in Python... so [1,2,3] or 'something else' is [1,2,3], but [] or 'something else' is 'something else'. If the latter is a one-item list, min() will always return its only item.Ammeter
Unfortunately this doesn't work for empty iterators.Tytybald
R
16

Catch and handle the exception.

try:
    print(min(l), max(l))
except (ValueError, TypeError):
    print('empty list or invalid input')

ValueError is raised with an empty sequence. TypeError is raised when the sequence contains unorderable types.

Remember answered 13/4, 2014 at 22:3 Comment(2)
this is prefered way to do this in python (exceptions are cheap): docs.python.org/3/glossary.html#term-eafpDinsmore
There's a side-effect: if some other error occurs lower on the stack that happens to be of the same type, it'll be caught too. This inaccuracy is the primary source of critique for exception handling. In this particular case, this is probably of little concern though.Causeuse

© 2022 - 2024 — McMap. All rights reserved.