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

Find word in list python

Let’s say I have a list of unknown words:

l = [‘bike’, ‘blue car’, ‘wheel’, ‘car’]

I would like to write a script to determine which word appears twice in the list.
What is the best way to do that ?

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

>Solution :

sum([1 if 'car' in word else 0 for word in l])

As noted, this overcounts for words that have the letters ‘car’ in them like "care", "scar", etc…

In which case, it’s better to just split along spaces.

sum([1 if 'car' in word.split() else 0 for word in l])

More generic word count dictionary:

from collections import defaultdict

count = defaultdict(int)

for words in l:
    for word in words.split():
        count[word] += 1
        
print(count)
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