Manage empty list/invalid input when finding max/m

2020-06-06 17:18发布

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?

3条回答
爷、活的狠高调
2楼-- · 2020-06-06 18:06

Specifying a default in earlier versions of Python:

max(lst or [0])
max(lst or ['empty list'])
查看更多
\"骚年 ilove
3楼-- · 2020-06-06 18:17

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.

查看更多
Root(大扎)
4楼-- · 2020-06-06 18:19

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.

查看更多
登录 后发表回答