Why does the 'int' object is not callable error occur when using the sum() function?
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.
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's elements
>>> print total
233168
If you shadow the sum
builtin, you can get the error you are seeing
>>> sum = 0
>>> total = sum(data3) # calculate sum of data3 list's elements
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
Also, note that sum
will work fine on the set
there is no need to convert it to a list
This means that somewhere else in your code, you have something like:
sum = 0
Which shadows the builtin sum (which is callable) with an int (which isn't).
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:
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 also comes in handy if you happened to assign a value to any other builtin, like dict
or list