Search code examples
pythonlistfor-loopcountsum

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:

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