Question

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.

Was it helpful?

Solution

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:

result += [k*k]

OTHER TIPS

result is a list object (with no entries, initially).

The += operator on a list is basically the same as calling its extend 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.) The extend method for a list tries to iterate over the (single) argument, and int 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. For result.append(k*k),whether k is a string or number,result gets sequentially additions.

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.

        lst1 =[3,4,5,6]
        def square(lst1):
            lst2  = []
            for num in lst1:
                lst2.append(num**2)
            return lst2
        #print(list(map(square,lst1))) # this will raise ''int' object is not iterable'
        print(list(map(square,list(lst1))))  # here making lst1 as list of list fixs the iterable problem i.e lst1 =[[3,4,5,6]]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top