+ 4

.remove() in list !

Why does it removes only the odds? What are the steps!? a=[0 ,1 , 2, 3, 4, 5, 6, 7, 8, 9, 10] for i in a: print(i) a.remove(i) Output is: 0 2 4 6 8 10

5th Jul 2018, 6:08 PM
Dolan
Dolan - avatar
5 Antworten
+ 6
This would work fine as it deletes from the end to the beginning. a=[0 ,1 , 2, 3, 4, 5, 6, 7, 8, 9, 10] for i in reversed(a): print(i) a.remove(i)
5th Jul 2018, 6:47 PM
John Wells
John Wells - avatar
+ 5
Once you remove, everything shifts their position. That screws up the indexing. Always reverse index, when removing, as the shifting stuff has already been processed.
5th Jul 2018, 6:17 PM
John Wells
John Wells - avatar
+ 4
1: a=[0 ,1 , 2, 3, 4, 5, 6, 7, 8, 9, 10] 2: for i in a: 3: print(i) 4: a.remove(i) When line 2 executes, i is 0 so line 4 removes it. Now, a is [1 , 2, 3, 4, 5, 6, 7, 8, 9, 10]. Line 2 now grabs the second number 2 and it gets removed.
5th Jul 2018, 6:42 PM
John Wells
John Wells - avatar
+ 3
Sorry John This time it’s not clear to me yet :-(
5th Jul 2018, 6:30 PM
Dolan
Dolan - avatar
+ 2
Try it this way my friend, the problem is that size of the list decreased every time you call remove function but using list function again it makes a copy then you can manipulate the list as you like. a=[0 ,1 , 2, 3, 4, 5, 6, 7, 8, 9, 10] for i in list(a): print(i) a.remove(i)
5th Jul 2018, 7:13 PM
SEMOOOOOOZ
SEMOOOOOOZ - avatar