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?.