Python for loop and iterator behavior

前端 未结 6 1780
迷失自我
迷失自我 2020-12-01 09:23

I wanted to understand a bit more about iterators, so please correct me if I\'m wrong.

An iterator is an object which has a pointer to the next object a

6条回答
  •  [愿得一人]
    2020-12-01 09:35

    There is an iterator protocol in python that defines how the for statement will behave with lists and dicts, and other things that can be looped over.

    It's in the python docs here and here.

    The way the iterator protocol works typically is in the form of a python generator. We yield a value as long as we have a value until we reach the end and then we raise StopIteration

    So let's write our own iterator:

    def my_iter():
        yield 1
        yield 2
        yield 3
        raise StopIteration()
    
    for i in my_iter():
        print i
    

    The result is:

    1
    2
    3
    

    A couple of things to note about that. The my_iter is a function. my_iter() returns an iterator.

    If I had written using iterator like this instead:

    j = my_iter()    #j is the iterator that my_iter() returns
    for i in j:
        print i  #this loop runs until the iterator is exhausted
    
    for i in j:
        print i  #the iterator is exhausted so we never reach this line
    

    And the result is the same as above. The iter is exhausted by the time we enter the second for loop.

    But that's rather simplistic what about something more complicated? Perhaps maybe in a loop why not?

    def capital_iter(name):
        for x in name:
            yield x.upper()
        raise StopIteration()
    
    for y in capital_iter('bobert'):
        print y
    

    And when it runs, we use the iterator on the string type (which is built into iter). This in turn, allows us run a for loop on it, and yield the results until we are done.

    B
    O
    B
    E
    R
    T
    

    So now this begs the question, so what happens between yields in the iterator?

    j = capital_iter("bobert")
    print i.next()
    print i.next()
    print i.next()
    
    print("Hey there!")
    
    print i.next()
    print i.next()
    print i.next()
    
    print i.next()  #Raises StopIteration
    

    The answer is the function is paused at the yield waiting for the next call to next().

    B
    O
    B
    Hey There!
    E
    R
    T
    Traceback (most recent call last):
      File "", line 13, in 
        StopIteration
    

提交回复
热议问题