faqts : Computers : Programming : Languages : Python : Common Problems : Lists

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

32 of 37 people (86%) answered Yes
Recently 10 of 10 people (100%) answered Yes

Entry

How can I remove a number of items from a list using a loop?
How can I modify a list while traversing it in one pass?

Mar 8th, 2005 17:27
Jacek Trzmiel, Federico Vicente III C. Sevilla, unknown unknown, Bjorn Pettersen, Federico Sevilla III


The "obvious" way:
  for x in list[:]:  # create a copy
    if f(x):
      list.remove(x)
Perhaps faster:
  for i in range(len(list)-1, -1, -1):
    x = list[i]
    if f(x):
      list.remove(x)
Which traverses the list backwards, so should be more resistant to the
list changing.
Alternatively you can do the reverse traversal using a counter and a
while loop, which perhaps may save space versus range() which uses
another list.
  i = len(list) - 1
  while (i >= 0):
    x = list[i]
    if f(x):
      del list[i]
    i -= 1          # You need at least Python 2 to use this notation
                    # Otherwise use i = i - 1