“Can only iterable” Python error

前端 未结 3 1917
面向向阳花
面向向阳花 2021-01-16 12:34

Hello my fellow programmers.

I am a fairly new programmer, and now I am facing a great predicament. I am getting the error:

can only assign an iterab         


        
3条回答
  •  北恋
    北恋 (楼主)
    2021-01-16 13:26

    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 "", line 1, in 
        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 "", line 1, in 
        for x in 1:pass
    TypeError: 'int' object is not iterable
    

提交回复
热议问题