What exactly are iterator, iterable, and iteration?

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

    Other people already explained comprehensively, what is iterable and iterator, so I will try to do the same thing with generators.

    IMHO the main problem for understanding generators is a confusing use of the word “generator”, because this word is used in 2 different meanings:

    1. as a tool for creating (generating) iterators,
      • in the form of a function returning an iterator (i.e. with the yield statement(s) in its body),
      • in the form of a generator expression
    2. as a result of the use of that tool, i.e. the resulting iterator.
      (In this meaning a generator is a special form of an iterator — the word “generator” points out how this iterator was created.)

    Generator as a tool of the 1st type:

    In[2]: def my_generator():
      ...:     yield 100
      ...:     yield 200
    
    In[3]: my_generator
    
    Out[3]: 
    
    In[4]: type(my_generator)
    
    Out[4]: function
    

    Generator as a result (i.e. an iterator) of the use of this tool:

    In[5]: my_iterator = my_generator()
    In[6]: my_iterator
    
    Out[6]: 
    
    In[7]: type(my_iterator)
    
    Out[7]: generator
    

    Generator as a tool of the 2nd type — indistinguishable from the resulting iterator of this tool:

    In[8]: my_gen_expression = (2 * i for i in (10, 20))
    In[9]: my_gen_expression
    
    Out[9]:  at 0x000000000542C048>
    
    In[10]: type(my_gen_expression)
    
    Out[10]: generator
    

提交回复
热议问题