trig trig - 7 months ago 35
Python Question

Python: TypeError: 'int' object is not iterable(Think Python 10.3)

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]
[1, 3, 6]

I get a
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!


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

res += a

Instead do


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:

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