Difference between Python's Generators and Iterators

后端 未结 11 1352
谎友^
谎友^ 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:28

    You can compare both approaches for the same data:

    def myGeneratorList(n):
        for i in range(n):
            yield i
    
    def myIterableList(n):
        ll = n*[None]
        for i in range(n):
            ll[i] = i
        return ll
    
    # Same values
    ll1 = myGeneratorList(10)
    ll2 = myIterableList(10)
    for i1, i2 in zip(ll1, ll2):
        print("{} {}".format(i1, i2))
    
    # Generator can only be read once
    ll1 = myGeneratorList(10)
    ll2 = myIterableList(10)
    
    print("{} {}".format(len(list(ll1)), len(ll2)))
    print("{} {}".format(len(list(ll1)), len(ll2)))
    
    # Generator can be read several times if converted into iterable
    ll1 = list(myGeneratorList(10))
    ll2 = myIterableList(10)
    
    print("{} {}".format(len(list(ll1)), len(ll2)))
    print("{} {}".format(len(list(ll1)), len(ll2)))
    

    Besides, if you check the memory footprint, the generator takes much less memory as it doesn't need to store all the values in memory at the same time.

提交回复
热议问题