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?

1
  • 3
    Very common mistake. Never modify a list while iterating through it. The answers below provide the correct method for achieving the desired result Commented Jun 25, 2014 at 13:35

1 Answer 1

12

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 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.