4

I am having trouble understanding why my code is failing to work. I am trying to remove words from a list that are only one character in length:

line = ['word','a','b','c','d','e','f','g']
for words in line:
    if len(words) == 1:
        line.remove(words)

This code returns this (which looks to remove 'every other' single character):

>>> line
['word', 'b', 'd', 'f']

Can anyone explain why this isn't working properly and how to fix?

Zero Piraeus
  • 52,181
  • 26
  • 146
  • 158
MorganTN
  • 2,567
  • 3
  • 11
  • 10
  • 3
    Very common mistake. Never modify a list while iterating through it. The answers below provide the correct method for achieving the desired result – sshashank124 Jun 25 '14 at 13:35

1 Answers1

11

Do this:

line = ['word','a','b','c','d','e','f','g']
line = [i for i in line if len(i) > 1]

The problem with your code is that you are removing from list while iterating which is not safe. It will change the length of list:

line = ['word','a','b','c','d','e','f','g']
iterated = 0
removed = 0
for words in line:
    iterated += 1
    if len(words) == 1:
        line.remove(words)
        removed += 1

print line # ['word', 'b', 'd', 'f']
print iterated # 5
print removed # 4
Aamir Rind
  • 36,955
  • 19
  • 118
  • 157