+ 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
5 Answers
+ 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)
+ 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.
+ 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.
+ 3
Sorry John This time itâs not clear to me yet :-(
+ 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)