What exactly are iterator, iterable, and iteration?

前端 未结 13 1672
遥遥无期
遥遥无期 2020-11-21 05:27

What is the most basic definition of \"iterable\", \"iterator\" and \"iteration\" in Python?

I have read multiple definitions but I am unable to identify the exact m

13条回答
  •  情深已故
    2020-11-21 05:44

    An iterable is a object which has a __iter__() method. It can possibly iterated over several times, such as list()s and tuple()s.

    An iterator is the object which iterates. It is returned by an __iter__() method, returns itself via its own __iter__() method and has a next() method (__next__() in 3.x).

    Iteration is the process of calling this next() resp. __next__() until it raises StopIteration.

    Example:

    >>> a = [1, 2, 3] # iterable
    >>> b1 = iter(a) # iterator 1
    >>> b2 = iter(a) # iterator 2, independent of b1
    >>> next(b1)
    1
    >>> next(b1)
    2
    >>> next(b2) # start over, as it is the first call to b2
    1
    >>> next(b1)
    3
    >>> next(b1)
    Traceback (most recent call last):
      File "", line 1, in 
    StopIteration
    >>> b1 = iter(a) # new one, start over
    >>> next(b1)
    1
    

提交回复
热议问题