Problem

Python

Consider the following list,

numbers = list(range(10))
print(numbers)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Now run the following code, given the above list. Explain the weird behavior that you observe.

for n in numbers:
    i = len(numbers)//2
    del numbers[i]
    print ('n={}, del {}'.format(n,i), numbers)

Solution

Python
numbers = list(range(10))
for n in numbers:
    i = len(numbers)//2
    del numbers[i]
    print ('n={}, del {}'.format(n,i), numbers)
n=0, del 5 [0, 1, 2, 3, 4, 6, 7, 8, 9]
n=1, del 4 [0, 1, 2, 3, 6, 7, 8, 9]
n=2, del 4 [0, 1, 2, 3, 7, 8, 9]
n=3, del 3 [0, 1, 2, 7, 8, 9]
n=8, del 3 [0, 1, 2, 8, 9]

What is happening is that the list over which we are looping changes its content because of the modifications during on the list in the for-loop. The message in this exercise is to never modify a list that you are looping over. Modification is indeed technically possible, as shown above, but you need to know what you are doing. Otherwise, you will experience very strange program behavior.

Comments