+ 1
Why i in for loop only goes to even indices
2 Réponses
+ 4
Your code calls for an iteration of range(8), but removes i, the iteration.
So, Range(8) = 0,1,2,3,4,5,6,7
1st iteration removes index[0].
Range is now = 1,2,3,4,5,6,7
2nd iteration removes index[1] which is now 2
Range is now = 1,3,4,5,6,7
3rd iteration removes index[2] which is now 4
Range is now 1,3,5,6,7
You see the pattern developing I hope.
Final line in code states:
print(sum(range)
Which is 1+3+5+7 =16
+ 3
in will check the length of the list each iteration of the loop yet increments the index by 1 each time. The loop removes the element at that index and the list is shortened and updated prior to the next iteration of the loop. To understand better try using:
for index, element in enumerate(myl):
print(index, element, myl)
myl.remove(i)