16

Let's say I have two lists list1 and list2 as:

list1 = [ 3, 4, 7 ]
list2 = [ 5, 2, 3, 5, 3, 4, 4, 9 ]

I want to find the count of the elements of list1 which are present in list2.

Expected output is 4 because 3 and 4 from list1 are appearing twice in list2. Hence, total count is as 4.

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
Thomas Lee
  • 173
  • 1
  • 1
  • 4

4 Answers4

29

Use list comprehension and check if element exists

c =  len([i for i in list2 if i in list1 ])

Better one from @Jon i.e

c = sum(el in list1 for el in list2)

Output : 4

Bharath M Shetty
  • 30,075
  • 6
  • 57
  • 108
  • 7
    Why build a list here... while the check isn't effficient because of lists, you may as well write this as `sum(el in list1 for el in list2)` – Jon Clements Oct 21 '17 at 11:03
  • Hi, what if I want to know the count of each element in a list, as the results would be: [2, 2, 0] – Anis Boudieb Jul 27 '20 at 17:05
4

You may use sum(...) to achieve this with the generator expression as:

>>> list1 = [ 3, 4, 7 ]
>>> list2 = [ 5, 2, 3, 5, 3, 4, 4, 9 ]

#         v returns `True`/`False` and Python considers Boolean value as `0`/`1`
>>> sum(x in list1 for x in list2)
4 

As an alternative, you may also use Python's __contains__'s magic function to check whether element exists in the list and use filter(..) to filter out the elements in the list not satisfying the "in" condition. For example:

>>> len(list(filter(list1.__contains__, list2)))
4

# Here "filter(list(list1.__contains__, list2))" will return the 
# list as: [3, 3, 4, 4]

For more details about __contains__, read: What does __contains__ do, what can call __contains__ function?.

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
2

You can iterate first list and add occurences of a given number to a sum using count method.

for number in list1: 
   s += list2.count(number);
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
1

You can use collections.Counter here, so a naive and rather ugly implementation first (mine).

list1 = [ 3, 4, 7 ]
list2 = [ 5, 2, 3, 5, 3, 4, 4, 9 ]
from collections import Counter
total = 0 
c = Counter(list2)
for i in list1: 
  if c[i]: 
    total += c[i]

This doesn't take into account what happens if you've got duplicates in the first list (HT Jon), and a much more elegant version of this would be:

counter = Counter(list2)
occurrences = sum(counter[v] for v in set(list1))
Withnail
  • 3,128
  • 2
  • 30
  • 47