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

How to count how many times a word in a list appeared in-another list

I have 2 lists and I want to see how many of the text in list 1 is in list 2 but I don’t really know of a way to like combine them the output isn’t summed and I have tried sum method but it does it for all words counted not each word.

Code:

l1 = ['hello', 'hi']
l2 = ['hey', 'hi', 'hello', 'hello']
for i in l2:
    print(f'{l1.count(i)}: {i}')

Output:

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

0: hey
1: hi
1: hello
1: hello

What I want is something more like this:

0: hey
1: hi
2: hello

>Solution :

I think a simple fix is to just flip the way you are looping through the lists:

l1 = ['hello', 'hi']
l2 = ['hey', 'hi', 'hello', 'hello']
for i in l1:
    print(f'{l2.count(i)}: {i}')

Output:

2: hello
1: hi
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