“Can only iterable” Python error

寵の児 提交于 2019-12-01 13:54:49

int_lis[:] = duplic_int_lis [int_firs] means assign all the items of duplic_int_lis [int_firs] to int_lis, so it expects you to pass an iterable/iterator on the RHS.

But in your case you're passing it an non-iterable, which is incorrect:

>>> lis = range(10)
>>> lis[:] = range(5) 
>>> lis               #all items of `lis` replaced with range(5)
[0, 1, 2, 3, 4]

>>> lis[:] = 5        #Non-iterable will raise an error.
Traceback (most recent call last):
  File "<ipython-input-77-0704f8a4410d>", line 1, in <module>
    lis[:] = 5
TypeError: can only assign an iterable

>>> lis[:] = 'foobar' #works for any iterable/iterator
>>> lis
['f', 'o', 'o', 'b', 'a', 'r']

As you cannot iterate over an integer, hence the error.

>>> for x in 1: pass
Traceback (most recent call last):
  File "<ipython-input-84-416802313c58>", line 1, in <module>
    for x in 1:pass
TypeError: 'int' object is not iterable

The RHS of a slice-assignment must be an iterable, not a scalar. Consider slice-deleting and then appending instead.

An iterable is a thing with multiple items that you can iterate through (for example: take the 1st value do something, then the 2nd do something, etc...) Lists, dictionaries, tuples, strings have several items in them and can be used as iterables. As a counterexample: number types don't qualify as iterable.

Remember that computers count from #0 so: if you want the first value of a list you can use

my_list[0]

before you go further I would suggest watching this video about looping. https://www.youtube.com/watch?v=EnSu9hHGq5o

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