Confused with python lists: are they or are they not iterators?

前端 未结 4 1699
深忆病人
深忆病人 2020-12-02 08:25

I am studying Alex Marteli\'s Python in a Nutshell and the book suggests that any object that has a next() method is (or at least can be used as) an ite

4条回答
  •  情话喂你
    2020-12-02 09:24

    List is not iterator but list contains an iterator object __iter__ so when you try to use for loop on any list, for loop calls __iter__ method and gets the iterator object and then it uses next() method of list.

    x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    it = x.__iter__()
    

    Now it contains iterator object of x which you can use as it.next() until StopIteration exception is thrown

提交回复
热议问题