0

I trying to solve Think Python exercise 10.3

Write a function that takes a list of numbers and returns the cumulative sum; that is, a new list where the ith element is the sum of the first i + 1 elements from the original list. For example, the cumulative sum of [1, 2, 3] is [1, 3, 6].

I get a TypeError with this code:

def culm_sum(num):
    res= []
    a = 0
    for i in num:
        a += i
        res += a
    return res

When I call culm_sum([1, 2, 3]) I get

TypeError: 'int' object is not iterable

Thank you!

1

2 Answers 2

3

The code you are using to append to your list is incorrect:

res += a

Instead do

res.append(a)

What's wrong with res += a? Python expects a to be iterable and behind the scenes tries to do the equivalent of:

for item in a:
    res.append(a)

But since a is not iterable, so you get a TypeError.

Note I initially thought your error was in for i in num: because your variable was poorly named. It sounds like it's a single integer. Since it is a list of numbers at least make it plural (nums) so that readers of your code are not confused. (The reader you will usually be helping is future you.)

Sign up to request clarification or add additional context in comments.

1 Comment

HI, thank you for your advice and your edit of my post! Didn't see that before! It works now! Also thank you for your advice on the variable name!
0

What you are trying to do this is extend your list with an int, which is not iterable, and hence the error. You need to add the element to the list using the append method :

res.append(a)

Or, do this, the correct way to extend :

res += [a]

1 Comment

I don't mention res += [a] in my answer because it's a bad habit to create temporary objects needlessly when another simple alternative exists.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.