+ 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????

20th Apr 2020, 4:40 AM
jigoku_tenshi
4 Respostas
+ 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
20th Apr 2020, 4:53 AM
Arsenic
Arsenic - avatar
+ 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)
20th Apr 2020, 11:06 AM
Varun Vaswani
Varun Vaswani - avatar
+ 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]".
20th Apr 2020, 5:09 AM
kiclause
kiclause - avatar
+ 1
Love the explanations! Thanks everyone!
20th Apr 2020, 3:11 PM
jigoku_tenshi