Digit_sum list


Hi all,

First time poster here and very new to python, so sorry if something doesn't make sense!

I'm trying to figure out how to get the sum of a list of numbers.

I've figured out how to do it with just one input as below:

x = 1234

def digit_sum(n):
    sum_n = 0
    while n>0:
        sum_n += (n%10)
    return sum_n

e.g. 1234 = 1+2+3+4 = 10

But i can't figure out how to do it with a list, this is my script at the moment:

y = [1234, 5678, 3456]

def digit_test(n):
    sum_n = []
    for i in n:
        while i>0:
            sum_n += (i%10)
            i = i//10
        return sum_n

print digit_test(y)

I would like the above to equal [10, 26, 18]

It just returns this error:
Traceback (most recent call last):
File "python", line 35, in
File "python", line 31, in digit_test
TypeError: 'int' object is not iterable.

It's the while loop i've got a problem with, i'm able to apply a function to each element in the list when a while loop isn't needed, but for this i do.

Does anyone have any idea?




this goes outside the scope of the exercise

we still need an integer to get the digit of 1234, 5678 and 3456 (Besides sum_n), so for example:

for i in n:
    total = 0

then in the while loop we need to increase total rather then sum_n, then after the loop we can append total to sum_n

a function ends the moment a return keyword is reached, so make sure return it completely outside the for loop as well


You're a star! Thanks for this.


You do understand why i placed total = 0 inside the for loop? Nicely done, i just gave a little nutch in the right direction and you solved it :smiley:


Yes thanks it was a good explanation! I should've realised I didn't have a value inside the 'for loop' to put the new values into, I tried the append previously but it obviously didn't work.

Thanks for the help!


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.