What exactly are iterator, iterable, and iteration?

前端 未结 13 1947
遥遥无期
遥遥无期 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:56

    Before dealing with the iterables and iterator the major factor that decide the iterable and iterator is sequence

    Sequence: Sequence is the collection of data

    Iterable: Iterable are the sequence type object that support __iter__ method.

    Iter method: Iter method take sequence as an input and create an object which is known as iterator

    Iterator: Iterator are the object which call next method and transverse through the sequence. On calling the next method it returns the object that it traversed currently.

    example:

    x=[1,2,3,4]
    

    x is a sequence which consists of collection of data

    y=iter(x)
    

    On calling iter(x) it returns a iterator only when the x object has iter method otherwise it raise an exception.If it returns iterator then y is assign like this:

    y=[1,2,3,4]
    

    As y is a iterator hence it support next() method

    On calling next method it returns the individual elements of the list one by one.

    After returning the last element of the sequence if we again call the next method it raise an StopIteration error

    example:

    >>> y.next()
    1
    >>> y.next()
    2
    >>> y.next()
    3
    >>> y.next()
    4
    >>> y.next()
    StopIteration
    

提交回复
热议问题