Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

count occurrences of list items in second list in python

a = list([1, 2, 3, 4, 5, 6, 7, 8, 9, 0])
b = list([1, 3, 6, 9])

How do I count the number of times an item in list be occurs in list a?

The above example should return a value of 4.

Whilst writing this question, I thought of the following (which appears to work)

a = list([1, 2, 3, 4, 5, 6, 7, 8, 9, 0])
b = list([1, 3, 6, 9])
c = 0
for n in b:
    if n in a:
        c += 1
        continue
print (c)

But there must be a neater way using list comparisons or something?

like image 509
Escribblings Avatar asked Apr 23 '19 11:04

Escribblings


1 Answers

You can use built-in sum:

sum(i in b for i in a)

Output:

4
like image 106
Chris Avatar answered Sep 27 '22 18:09

Chris