0

If I have 2 lists, for an example:

list_1 = ['a', 'A']
list_2 = ['a', 'A', 'A', 'b', 'b', 'b', 'b']

How can I make a count to see how many times the items from list_1 appear in list_2?

So in this case it should return 3.

  • Does this answer your question? [How to find list intersection?](https://stackoverflow.com/questions/3697432/how-to-find-list-intersection) – Random Davis Jan 06 '22 at 19:19

5 Answers5

1
list_1 = ['a', 'A']
list_2 = ['a', 'A', 'A', 'b', 'b', 'b', 'b']

found = 0
for x in list_1:
    for y in list_2:
        if x == y:
            found += 1
print(found)
Cameron
  • 389
  • 1
  • 9
  • 1
    The complexity is bad though. If increases quadratically with the size of the inputs as you need to cross check all elements. – mozway Jan 06 '22 at 19:23
1

An efficient O(n) method using a set as reference:

list_1 = ['a', 'A']
list_2 = ['a', 'A', 'A', 'b', 'b', 'b', 'b']

set_1 = set(list_1)

count = 0
for e in list_2:
    if e in set_1:
        counter += 1

Output: 3

mozway
  • 194,879
  • 13
  • 39
  • 75
1

A one liner:

sum([x == y for x in list_1 for y in list_2])
Ahmed Elashry
  • 389
  • 2
  • 12
0

Another solution, which could be beneficial in other cases, because the Counter()- object returns a dictionary with the already summed up elements

from collections import Counter

list_1 = ['a', 'A']
list_2 = ['a', 'A', 'A', 'b', 'b', 'b', 'b']

c = Counter(list_2)
print(sum([c[x] for x in list_1]))
baskettaz
  • 741
  • 3
  • 12
0

Just use count for lists:

print(list_2.count(list_1[0]) + list_2.count(list_1[1]))

or in a loop:

sum_ = 0
for i in range(len(list_1)):
    sum_ += list_2.count(list_1[i])
print(sum_)
Ali_Sh
  • 2,667
  • 3
  • 43
  • 66