0

I want to get the sum of the digits of an integer, and found the solutions below:

  1. sum(map(int,list(str(123))))

  2. sum(int(digit) for digit in str(123))

However, when I run this, I get the below error:

TypeError: 'int' object is not callable

10 Rep
  • 2,217
  • 7
  • 19
  • 33
  • 2
    Did you set the name `sum` to an integer? – khelwood Jun 26 '20 at 15:23
  • 1
    @khelwood: Or `str`, or, in the former example, `list`. Point is, this is clearly a name-shadowing conflict; don't name variables the same as built-ins. If this is an interactive session you don't want to restart, run `del sum`, `del list`, `del str` (ignore any errors) and your code should work fine. – ShadowRanger Jun 26 '20 at 15:25
  • 1
    [Works for me](https://tio.run/##K6gsycjPM/7/v6AoM69Eo7g0VyM3sUADyNbJySwGCpQUaRgaGWuCwP//AA) – pppery Jun 27 '20 at 00:34

4 Answers4

2

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?

Ronie Martinez
  • 1,254
  • 1
  • 10
  • 14
1

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!

  • 1
    `sum(int(digit) for digit in str(123))` is valid Python working as intended. If your function has only one argument, then you're not required to use round brackets / parenthesis to write a generator expression. Check [PEP 289](https://www.python.org/dev/peps/pep-0289/) for more details. – Unatiel Jun 26 '20 at 15:45
  • 1
    Edited. My mistake. – Nivardo Albuquerque Jun 26 '20 at 15:47
1
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.

10 Rep
  • 2,217
  • 7
  • 19
  • 33
Arif Oyong
  • 392
  • 1
  • 3
  • 11
0

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)])
Mntfr
  • 483
  • 6
  • 20
  • `sum(int(digit) for digit in str(123))` is valid Python working as intended. If your function has only one argument, then you're not required to use round brackets / parenthesis to write a generator expression. Check [PEP 289](https://www.python.org/dev/peps/pep-0289/) for more details. – Unatiel Jun 26 '20 at 15:47