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

半腔热情 提交于 2019-12-12 19:25:24

问题


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.


回答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]



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




回答3:


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.




回答4:


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


来源:https://stackoverflow.com/questions/17645500/typeerror-int-object-is-not-iterable-why-its-happening

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!