Python For Loop List Interesting Result

前端 未结 4 1910
执念已碎
执念已碎 2021-01-25 07:42
a = [0,1,2,3,4,5]
for b in a:
  print \":\"+str(b)
  a.pop(0)

Thinking that this would work in order going through the entire list and all its items I

4条回答
  •  一生所求
    2021-01-25 08:16

    You are looping over a list and altering it at the same time. By using .pop() you are shortening the list, but the iterator pointer is not updated.

    Use a copy instead:

    for b in list(a):
    

    or

    for b in a[:]:
    

    where the [:] slice notation returns a list copy.

    Another approach would be to use a while loop instead:

    while a:
        print a.pop(0)
    

    because an empty list tests as boolean False.

    The python for loop uses it's argument as an iterator, it does not itself keep an index. There is no way for the for loop to 'know' you removed elements. Instead, it's the list() iterator that keeps that pointer:

    >>> a = [0,1,2,3,4,5]
    >>> itera = iter(a)
    >>> itera.next()  # index 0 -> a[0] is 0
    0
    >>> a.pop(0)
    0
    >>> a
    [1,2,3,4,5]
    >>> itera.next()  # index 1 -> a[1] is 2
    2
    

    That iterator keeps a counter, and every time you call next() on the iterator it'll give you the value at the next index, whatever that value may be, until the counter is equal to the current lenght of the list.

提交回复
热议问题