A safe max() function for empty lists

后端 未结 7 1161
天命终不由人
天命终不由人 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:41

    Another solution could be by using ternary operators:

    nums = []
    max_val = max(nums) if nums else 0
    

    or

    max val = max(iter(nums) if nums else [0])
    

提交回复
热议问题