Why i in for loop only goes to even indices | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita
+ 1

Why i in for loop only goes to even indices

https://code.sololearn.com/c97T44oF1ItW/?ref=app

18th Apr 2020, 11:22 AM
ashu pandey
ashu pandey - avatar
2 Respuestas
+ 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
18th Apr 2020, 11:43 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 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)
18th Apr 2020, 11:49 AM
ChaoticDawg
ChaoticDawg - avatar