A safe max() function for empty lists

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

    The max of an empty sequence "should" be an infinitely small thing of whatever type the elements of the sequence have. Unfortunately, (1) with an empty sequence you can't tell what type the elements were meant to have and (2) there is, e.g., no such thing as the most-negative integer in Python.

    So you need to help max out if you want it to do something sensible in this case. In recent versions of Python there is a default argument to max (which seems to me a misleading name, but never mind) which will be used if you pass in an empty sequence. In older versions you will just have to make sure the sequence you pass in isn't empty -- e.g., by oring it with a singleton sequence containing the value you'd like to use in that case.

    [EDITED long after posting because Yaakov Belch kindly pointed out in comments that I'd written "infinitely large" where I should have written "infinitely small".]

提交回复
热议问题