Here is three examples actually.
>>> result = []
>>> for k in range(10):
>>> result += k*k
>>> result = []
>>> for k in range(10):
>>> result.append(k*k)
>>> result = [k*k for k in range(10)]
First one makes a error. Error prints like below
TypeError: 'int' object is not iterable
However, second and third one works well.
I could not understand the difference between those three statements.
I know this is too old but for anyone who lands here, this is a simple reproducible example to illustrate ''int' object is not iterable' error.
result
is a list object (with no entries, initially).The
+=
operator on a list is basically the same as calling itsextend
method on whatever is on the right hand side. (There are some subtle differences, not relevant here, but see the python2 programming FAQ for details.) Theextend
method for a list tries to iterate over the (single) argument, andint
is not iterable.(Meanwhile, of course, the
append
method just adds its (single) argument, so that works fine. The list comprehension is quite different internally, and is the most efficient method as the list-building is done with much less internal fussing-about.)You are iterating over an integer rather than a string or sequence. For
result += k*k
,only if k was a string/sequence input,then it would be true but if k is a number, result would be a continued summation. Forresult.append(k*k)
,whether k is a string or number,result gets sequentially additions.In-place addition on a list object extends the list with the elements of the iterable.
k*k
isn't an iterable, so you can't really "add" it to a list.You need to make
k*k
an iterable: