trig - 9 months ago 49

Python Question

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 firstelements from the original list. For example, the cumulative sum of`i + 1`

is`[1, 2, 3]`

.`[1, 3, 6]`

I get a

`TypeError`

`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])`

`TypeError: 'int' object is not iterable`

Thank you!

Answer Source

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.)