How does Python manage a 'for' loop internally?

前端 未结 4 1976
臣服心动
臣服心动 2021-02-02 12:55

I\'m trying to learn Python, and I started to play with some code:

a = [3,4,5,6,7]
for b in a:
    print(a)
    a.pop(0)
<         


        
4条回答
  •  梦如初夏
    2021-02-02 13:45

    AFAIK, the for loop uses the iterator protocol. You can manually create and use the iterator as follows:

    In [16]: a = [3,4,5,6,7]
        ...: it = iter(a)
        ...: while(True):
        ...:     b = next(it)
        ...:     print(b)
        ...:     print(a)
        ...:     a.pop(0)
        ...:
    3
    [3, 4, 5, 6, 7]
    5
    [4, 5, 6, 7]
    7
    [5, 6, 7]
    ---------------------------------------------------------------------------
    StopIteration                             Traceback (most recent call last)
     in ()
          2 it = iter(a)
          3 while(True):
    ----> 4     b = next(it)
          5     print(b)
          6     print(a)
    

    The for loop stops if the iterator is exhausted (raises StopIteration).

提交回复
热议问题