Sunday, October 28, 2012

How to remove item when looping through a list in Python

The best way is to make a copy of the list first. Like this:
words = ['xaa', 'sss', 'aaa', 'bbb']
for word in words[:]:
    if word[0] == 'x':
      words.remove(word)
At first, I use code like this to achieve my goal:
words = ['xaa', 'aaa', 'bbb', 'ccc']
for word in words:
  if word[0] == 'x':
    words.remove(word)
the behavior of this code is not ensured. Thera are some other ways to modify a list while looping through the list. But I stick to the copy method.

No comments:

Post a Comment