I want to get the sum of the digits of an integer, and found the solutions below:
sum(map(int,list(str(123))))
sum(int(digit) for digit in str(123))
However, when I run this, I get the below error:
TypeError: 'int' object is not callable
I want to get the sum of the digits of an integer, and found the solutions below:
sum(map(int,list(str(123))))
sum(int(digit) for digit in str(123))
However, when I run this, I get the below error:
TypeError: 'int' object is not callable
Contrary to other answers, both your code works fine.
I think you are shadowing something on your code. Perhaps you used int
as a variable?
sum()
works on iterables.
int(digit) for digit in str(123)
This returns an generator, and should work, as said by other answers, take a look at this answer.
The below should also do the job:
sum([int(digit) for digit in '123'])
Hope this helps!
sum(int(digit) for digit in str(123))
The above code should work.
However you said you get the error,
TypeError: 'int' object is not callable
That error suggests that you're using type int
instead of a str
.
Did you use another variable for that?
For example, the below code should give you that error you mentioned
obj = 123
sum(int(digit) for digit in obj)
You have to ensure that obj
is of a str
type.
sum()
works in iterable objects. You need to create a list with the digits you are trying to add. The code below should do that:
sum([int(x) for x in str(123)])