2

I have the following Python-code which is supposed to read through this list. If a word's length is not 3, the word should be removed from the list:

stuff = ["apple", "jam", "banana", "bread", "corn", "orange", "tea", "peanut"]

for word in stuff:
    if len(word) == 3:
        pass
    else:
        stuff.remove(word)

print(stuff)

But as I print the list, I get the following output:

['jam', 'bread', 'orange', 'tea']

But it should look like this:

['jam', 'tea']

Help would be highly appreciated!

1 Answers1

2

You shouldn't remove elements from a list while iterating over it, as some elements may be skipped. You can use a list comprehension instead.

stuff = ["apple", "jam", "banana", "bread", "corn", "orange", "tea", "peanut"]
res = [word for word in stuff if len(word) == 3]
print(res)
Unmitigated
  • 76,500
  • 11
  • 62
  • 80