Difference between Python's Generators and Iterators

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

    I am writing specifically for Python newbies in a very simple way, though deep down Python does so many things.

    Let’s start with the very basic:

    Consider a list,

    l = [1,2,3]
    

    Let’s write an equivalent function:

    def f():
        return [1,2,3]
    

    o/p of print(l): [1,2,3] & o/p of print(f()) : [1,2,3]

    Let’s make list l iterable: In python list is always iterable that means you can apply iterator whenever you want.

    Let’s apply iterator on list:

    iter_l = iter(l) # iterator applied explicitly
    

    Let’s make a function iterable, i.e. write an equivalent generator function. In python as soon as you introduce the keyword yield; it becomes a generator function and iterator will be applied implicitly.

    Note: Every generator is always iterable with implicit iterator applied and here implicit iterator is the crux So the generator function will be:

    def f():
      yield 1 
      yield 2
      yield 3
    
    iter_f = f() # which is iter(f) as iterator is already applied implicitly
    

    So if you have observed, as soon as you made function f a generator, it is already iter(f)

    Now,

    l is the list, after applying iterator method "iter" it becomes, iter(l)

    f is already iter(f), after applying iterator method "iter" it becomes, iter(iter(f)), which is again iter(f)

    It's kinda you are casting int to int(x) which is already int and it will remain int(x).

    For example o/p of :

    print(type(iter(iter(l))))
    

    is

    
    

    Never forget this is Python and not C or C++

    Hence the conclusion from above explanation is:

    list l ~= iter(l)

    generator function f == iter(f)

提交回复
热议问题