I'm trying to figure out why I'm getting an error when using the sum function on 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's elements
print total
And here is the error:
line 8, in <module> total2 = sum(data3)
TypeError: 'int' object is not callable
I found this explanation for the error:
In Python a "callable" is usually a function. The message means you are treating a number (an >"int") as if it were a function (a "callable"), so Python doesn't know what to do, so it >stops.
I've also read that sum() is capable of being used on lists, so I'm wondering what is going wrong here?
I just tried it in an IDLE module and it worked fine. However, it doesn't work in the python interpreter. Any ideas on how that can be?
In the interpreter its easy to restart it and fix such problems. If you don't want to restart the interpreter, there is another way to fix it:
This also comes in handy if you happened to assign a value to any other builtin, like
dict
orlist
You probably redefined your "sum" function to be an integer data type. So it is rightly telling you that an integer is not something you can pass a range.
To fix this, restart your interpreter.
If you shadow the
sum
builtin, you can get the error you are seeingAlso, note that
sum
will work fine on theset
there is no need to convert it to alist
This means that somewhere else in your code, you have something like:
Which shadows the builtin sum (which is callable) with an int (which isn't).