+ 1
I donât get it!
arr = [0,1,2,3,4,5,6] i=0 for _ in arr: del arr[i] i = i +1 print(arr) Output: [1,3,5] Shouldnât this code have deleted every element from the list????
4 Answers
+ 4
jigoku_tenshi , everytime you delete an element in the list the element next to it comes to that index but the iterator does not change that's why alternate elements gets deleted
+ 2
jigoky_tenshi , as others have also discussed, everytime you move an element from an iterator, the next element takes it's place. Instead, you should try to do this,
for i in arr:
arr.remove(i)
+ 1
â i=0
arr[0] (=0) is deleted.
âarr[0] is changed into 1.
(arr = [1,2,3,4,5,6])
âi=1
(â»"new arr[0] (=1)" has't been deleted)
âĄi=1
arr[1] (=2) is deleted.
âarr[1] is changed into 3.
(arr = [1,3,4,5,6])
âi=2
(â»"new arr[1] (=3)" has't been deleted)
âĄi=2
arr[2] (=4) is deleted.
âarr[2] is changed into 5.
(arr = [1,3,5,6])
âi=3
(â»"new arr[2] (=5)" has't been deleted)
âąi=3
arr[3] (=6) is deleted.
(arr = [1,3,5])
âi=4
Now, cursor reached the end of array. Loop finished.
So, you have the output,
"arr = [1,3,5]".
+ 1
Love the explanations! Thanks everyone!