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.
The most straightforward way to get the number of elements in a list is to use the Python built-in function len() . As the name function suggests, len() returns the length of the list, regardless of the types of elements in it.
We can directly call the __len__() member function of list to get the size of list i.e.
Using the count() Function The "standard" way (no external libraries) to get the count of word occurrences in a list is by using the list object's count() function. The count() method is a built-in function that takes an element as its only argument and returns the number of times that element appears in the list.
The easiest way to count the number of occurrences in a Python list of a given item is to use the Python . count() method. The method is applied to a given list and takes a single argument. The argument passed into the method is counted and the number of occurrences of that item in the list is returned.
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
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?.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With