TypeError: 'int' object is not iterable, why it's happening

12,598

Solution 1

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]

Solution 2

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

Share:
12,598
nextdoordoc
Author by

nextdoordoc

Updated on September 06, 2022

Comments

  • nextdoordoc
    nextdoordoc over 1 year

    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.