In the context of this exercise, using a
for loop to iterate through the list seems like a good solution. However this ends up generating wrong solutions, why doesn’t this work?
To understand why
for iteration breaks in this lesson we need to break down what happens as the list runs:
lst = [4, 8, 10, 11, 12, 15] for i in lst: del lst print(lst)
This code will let us take a look at how the code breaks down as it iterates through the list. So the results will be:
[8,10,11,12,15] #i = 4 (index 0) [10,11,12,15] #i = 10 (index 1 above) [11,12,15] #i = 12(index 2 above) #the loop will stop at this point, as there is no index 3
So because the list is shifted each time it runs, an element will be skipped with each pass and cause it to stop. In our example we would have expected to empty the list by the end but that was not the case. To give a hint regarding the code challenge, since
for doesn’t work if the list changes, what if you used
while? What kind of conditions would you be looking to maintain while moving through the list?
Feel free to discuss below and help each other with understanding this concept!