I know I'm not supposed to modify the list inside a loop, but just out of curiosity, I would like to know why the number of iterations is different between the following two examples.
Example 1:
x = [1, 2, 3, 4, 5]
for i, s in enumerate(x):
del x[0]
print(i, s, x)
Example 2:
x = [1,2,3,4,5]
for i, s in enumerate(x):
x = [1]
print(i, s, x)
Example 1 runs only 3 times because when i==3, len(x)==2.
Example 2 runs 5 times even though len(x)==1.
So my question is, does enumerate generate a full list of (index, value) pairs at the beginning of the loop and iterate through it? Or are they generated on each iteration of the loop?
differentvariable and keeps going with theoriginalvalue of x.forloop does not re-evaluate the iterator, so even if you re-assignxinside theforloop the loop will still use the old value. Obviously if you remove elements from a list, the loop will complete with less iterations.list(enumerate(...))