A safe max() function for empty lists

后端 未结 7 1222
天命终不由人
天命终不由人 2021-02-01 12:28

Evaluating,

max_val = max(a)

will cause the error,

ValueError: max() arg is an empty sequence

Is there a bett

7条回答
  •  独厮守ぢ
    2021-02-01 12:42

    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 "", line 1, in 
    ValueError: max() arg is an empty sequence
    

提交回复
热议问题