Difference between Python's Generators and Iterators

后端 未结 11 1217
谎友^
谎友^ 2020-11-22 05:20

What is the difference between iterators and generators? Some examples for when you would use each case would be helpful.

11条回答
  •  抹茶落季
    2020-11-22 05:27

    Iterators:

    Iterator are objects which uses next() method to get next value of sequence.

    Generators:

    A generator is a function that produces or yields a sequence of values using yield method.

    Every next() method call on generator object(for ex: f as in below example) returned by generator function(for ex: foo() function in below example), generates next value in sequence.

    When a generator function is called, it returns an generator object without even beginning execution of the function. When next() method is called for the first time, the function starts executing until it reaches yield statement which returns the yielded value. The yield keeps track of i.e. remembers last execution. And second next() call continues from previous value.

    The following example demonstrates the interplay between yield and call to next method on generator object.

    >>> def foo():
    ...     print "begin"
    ...     for i in range(3):
    ...         print "before yield", i
    ...         yield i
    ...         print "after yield", i
    ...     print "end"
    ...
    >>> f = foo()
    >>> f.next()
    begin
    before yield 0            # Control is in for loop
    0
    >>> f.next()
    after yield 0             
    before yield 1            # Continue for loop
    1
    >>> f.next()
    after yield 1
    before yield 2
    2
    >>> f.next()
    after yield 2
    end
    Traceback (most recent call last):
      File "", line 1, in 
    StopIteration
    >>>
    

提交回复
热议问题