Difference between Python's Generators and Iterators

后端 未结 11 1215
谎友^
谎友^ 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 05:38

    Examples from Ned Batchelder highly recommended for iterators and generators

    A method without generators that do something to even numbers

    def evens(stream):
       them = []
       for n in stream:
          if n % 2 == 0:
             them.append(n)
       return them
    

    while by using a generator

    def evens(stream):
        for n in stream:
            if n % 2 == 0:
                yield n
    
    • We don't need any list nor a return statement
    • Efficient for large/ infinite length stream ... it just walks and yield the value

    Calling the evens method (generator) is as usual

    num = [...]
    for n in evens(num):
       do_smth(n)
    
    • Generator also used to Break double loop

    Iterator

    A book full of pages is an iterable, A bookmark is an iterator

    and this bookmark has nothing to do except to move next

    litr = iter([1,2,3])
    next(litr) ## 1
    next(litr) ## 2
    next(litr) ## 3
    next(litr) ## StopIteration  (Exception) as we got end of the iterator
    

    To use Generator ... we need a function

    To use Iterator ... we need next and iter

    As been said:

    A Generator function returns an iterator object

    The Whole benefit of Iterator:

    Store one element a time in memory

提交回复
热议问题