Why is an int object not an error being caused when using the sum () function?

I am trying to understand why I get an error when using the sum function in a range.

Here is the code:

data1 = range(0, 1000, 3) data2 = range(0, 1000, 5) data3 = list(set(data1 + data2)) # makes new list without duplicates total = sum(data3) # calculate sum of data3 list elements print total 

And here is the error:

 line 8, in <module> total2 = sum(data3) TypeError: 'int' object is not callable 

I found this error explanation:

In Python, a "callable" is usually a function. The message means that you are handling the number (→ int) as if it were a function ("called"), so Python does not know what to do, therefore ita> stops.

I also read that sum () can be used in lists, so I wonder what is going wrong here?

I just tried it in the IDLE module and it worked fine. However, it does not work in the python interpreter. Any ideas on how this could be?

+7
source share
3 answers

You have probably redefined your function "sum" as an integer data type. Therefore, it is fair to tell you that an integer is not something that you can convey to a range.

To fix this, restart your interpreter.

 Python 2.7.3 (default, Apr 20 2012, 22:44:07) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> data1 = range(0, 1000, 3) >>> data2 = range(0, 1000, 5) >>> data3 = list(set(data1 + data2)) # makes new list without duplicates >>> total = sum(data3) # calculate sum of data3 list elements >>> print total 233168 

If you obscure the built-in sum , you may get the error message that you see

 >>> sum = 0 >>> total = sum(data3) # calculate sum of data3 list elements Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'int' object is not callable 

Also note that sum works fine on set , there is no need to convert it to list

+18
source

This means that somewhere else in your code there is something like:

 sum = 0 

Which hides the built-in amount (which is called) with int (which is not the case).

+16
source

It is easy to restart it in the interpreter and fix such problems. If you do not want to restart the interpreter, there is another way to fix it:

 Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> l = [1,2,3] >>> sum(l) 6 >>> sum = 0 # oops! shadowed a builtin! >>> sum(l) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'int' object is not callable >>> import sys >>> sum = sys.modules['__builtin__'].sum # -- fixing sum >>> sum(l) 6 

This is also useful if you are assigned a value to any other built-in, such as dict or list

+3
source

Source: https://habr.com/ru/post/919008/


All Articles