How to use max function in python? I'm getting

2019-03-02 13:20发布

问题:

>>> a = [1,2,3,4,5]

Max function gives TypeError: 'int' object is not callable

>>> max(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> max(1, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>>

回答1:

The error is clear: you have redefined max to be an int in your code. Or you use someone else's code that does that. So you probably have something like this somewhere

max = 4

This is why it is seen as very bad practice to use built-in names as variable names. Python allows you to do it, but it's error prone.

Prefer the use of maximum or max_ if you really want something close to max.



回答2:

It works:

In [1]: a = [1,2,3,4,5]

In [2]: max(a)
Out[2]: 5

If you have not shadowed max somewhere, everything works as expected.



回答3:

You have somewhere in your code defined a variable named max

max = something

Because:

a = [1,2,3,4,5]
print max(a)

Outputs 5 and works perfectly.



标签: python max