python - Why is list.remove only removing every second item? -
in python 2.7.2 idle interpreter:
>>> mylist = [1, 2, 3, 4, 5] >>> item in mylist: mylist.remove(item) >>> mylist [2, 4]
why?
it's because when iterate on list, python keeps track of index in list. consider following code instead:
for in range(len(mylist)): if >= len(mylist): break item = mylist[i] mylist.remove(item)
if track (which python doing in code), see when remove item in list, number right shifts 1 position left fill void left when removed item. right item @ index i
, never seen in iteration because next thing happens increment i
next iteration of loop.
now little clever. if instead iterate on list backward, we'll clear out list:
for item in reversed(mylist): mylist.remove(item)
the reason here we're taking item off end of list @ each iteration of loop. since we're taking items off end, nothing needs shift (assuming uniqueness in list -- if list isn't unique, result same, argument gets bit more complicated).
of course, if you're looking remove items list, can easily:
del mylist[:]
or slice assignment:
mylist[:] = []
(i mention latter because can useful replace segments of list other items don't need same length).
Comments
Post a Comment