Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Length of strings not recognized properly in Python?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

['jam', 'tea']

Help would be highly appreciated!

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading