-1

OK so i wrote this:

n=123465

def digit_sum(n):
    answer=[]
    n=str(n)

    for x in n:
        print x
        x = int(x)
        answer = answer.append(x)

    return sum(answer)

print digit_sum(n)

The problem is that I wrote answer = answer.append(x) when I should have wrote just answer.append(x). Can someone please tell me why I can't write answer = answer.append(x)?

jonrsharpe
  • 107,083
  • 22
  • 201
  • 376
Crazypigs
  • 89
  • 3
  • 13
  • Note: a more Pythonic way of doing the same is `sum(map(int, str(x)))`, or a more readable: `sum([int(i) for i in str(x)])` – ssm Jul 04 '14 at 05:52
  • 1
    @ssm No need for creating a list. `sum(int(x) for x in str(x))` would suffice. – Hyperboreus Jul 04 '14 at 06:10

2 Answers2

3

append always returns None when called on a list. Thus by executing a = a.append(x) you first append x to a and then you set a to None (the return value of append).

Hyperboreus
  • 31,109
  • 9
  • 45
  • 84
1

As @Hyperboreus answered append returns None. Not talking about adequacy of the code you can only concatenate list to list:

x = [int(x)]
answer += x

which is equal to answer.extend([int(x)]))
But sure more adequate is to just answer.append(int(x))
@ssm comment should be mentioned indeed as a pythonic way to implement the whole thing: sum(int(i) for i in str(x))

arbulgazar
  • 1,846
  • 1
  • 16
  • 23