max() give "int" not callable error in my function

Question:

I have a problem using max() inside my function. When a create a list with integers, max function works good. However when a create a list in my function and then using max() with my integer list then it gives “TypeError: ‘int’ object is not callable” error.
Where am I wrong and how can I fix it?

>>> a = [1,2,3,4,5] # A simple list
>>> max(a) # It works fine
>>> 5
>>> def palen(num):
...     min = 10**(num-1)
...     max = (10**num)-1
...     a=[] # Another list
...     mul=0
...     for i in range(max,min-1,-1):
...         for j in range (max,min-1,-1):
...             mul=i*j
...             if str(mul)==str(mul)[::-1]:
...                 a.append(mul)
...     return max(a)
...
>>> palen(2)
Traceback (most recent call last):
 File "<input>", line 1, in <module>
 File "<input>", line 11, in palen
TypeError: 'int' object is not callable
Asked By: skywalkerc

||

Answers:

On line 6 of your readout you define a variable called max. This shadows the pointer to max().
This is why you can’t use the max() function anymore.
You need to rename your variable max on line 6 and everywhere else you use it to fix this.

For more information on namespaces in Python see this interesting page I just found: http://bytebaker.com/2008/07/30/python-namespaces/

Answered By: Gullydwarf

Because you redefine max as a int number with

max = (10**num)-1

so you can not Call a number to help you get the max value of a list.
Change the variable name will be ok:

def palen(num):
  min_num = 10**(num-1)
  max_num = (10**num)-1
  a=[] # Another list
  mul=0
  for i in range(max_num,min_num-1,-1):
    for j in range (max_num,min_num-1,-1):
      mul=i*j
      if str(mul)==str(mul)[::-1]:
        a.append(mul)
  return max(a)

print palen(2)
Answered By: lqhcpsgbl

If we use max as variable name in earlier part of program, then we will encounter this problem. Advise is to not use max/min as variable name. Solution is to rename earlier variables with name max.

x=[1,2,3]
max(x)

Output:3

max=20
x=[1,2,3]
max(x)

enter image description here

Answered By: Ashish Anand

do not use max in any naming while programming
else if you can delete max variable from memory if not in use

use del(max) before calling max(arr) or similar situations

Answered By: Sanjay
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.