Search code examples
pythonbuffer-overflow

Why does a for loop stops unexpectedly during an iteration of a list while the list gets deleted?


The problem lies in the last for loop block. It should pop the expo list to complete vanishing but it stops at length 32. I cannot imagine why.

I tried the list.pop method and also as shown the del operator. Both raise the same error.

def generator(): # generator which generates like 2,4,8,16 -> 2 to the power of x
    list = range(1,65)
    for i in list:
        yield 2**i

mygen = generator() # generator object

expo = [] # empty list for the exponential values

for i in mygen: # for loop to put the values of the genertor in list form
    expo.append(i)
    print(expo)

for i in expo: # attempt to delete the last element, but stops at list with length 32
    del expo[-1]
    print(expo)

I expected that the list would get deleted as it was build stepwise. It should become [] but becomes len(expo)=32 .

So why does it stop ?


Solution

  • You are deleting the list you are iterating on, which ends up deleting only half the list, and then the iteration stops on 32 elements (since the length of the expo list is 64, half of it is 32

    You have two options:

    • Iterate on the copy of the list and delete the actual list .
    #Iterating on copy of expo
    for i in expo[:]:
        del expo[-1]
        print(expo)
    
    • Use list.clear to clear the list in one step instead of the for loop

    From the docs: https://docs.python.org/3/tutorial/datastructures.html

    list.clear()
    Remove all items from the list. Equivalent to del a[:].

    expo.clear()
    print(expo)
    #[]