Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Find count of the elements of one list in another list

Tags:

python

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.

like image 408
Thomas Lee Avatar asked Oct 21 '17 10:10

Thomas Lee


People also ask

How do I count a list inside a list in Python?

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.

How do I find the length of a nested list in Python?

We can directly call the __len__() member function of list to get the size of list i.e.

How do you count the number of occurrences of an element in a list?

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.

How do you count how many times a value appears in a list in Python?

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.


2 Answers

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

like image 192
Bharath Avatar answered Sep 18 '22 18:09

Bharath


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

like image 34
Moinuddin Quadri Avatar answered Sep 21 '22 18:09

Moinuddin Quadri