+ 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 Respuestas
+ 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!