Open In App

Python - Sum of each List element occurrence in another

Last Updated : 13 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Sometimes, while working with Python, we can have a problem in which we need to get occurrence of 1 element in another. But as a modification of this, we can have a problem in which we need to count the occurrence of all elements of 1 list in another. Lets discuss certain ways in which this task can be performed. 

Method #1 : Using nested loops This is one of the way in which this task can be performed. This is brute force way in which this task can be performed. In this, we iterate one list and then target list, if element match, we increase the counter. 


Output
The original list 1 is : [1, 3, 4, 5, 1, 4, 4, 6, 7]
The original list 2 is : [4, 6, 1]
The occurrence count : 6

Time Complexity : O(n*m), where n is length of test_list1 and m is length of test_list2

Auxiliary Space : O(n+m), where n is length of test_list1 and m is length of test_list2

  Method #2 : Using sum() + count() The combination of above methods can be used to perform this particular task. This is one liner alternative to the above method. In this counting is done using count() and accumulation using sum(). 


Output
The original list 1 is : [1, 3, 4, 5, 1, 4, 4, 6, 7]
The original list 2 is : [4, 6, 1]
The occurrence count : 6

Method 3:  using operator.countOf() method


Output
The original list 1 is : [1, 3, 4, 5, 1, 4, 4, 6, 7]
The original list 2 is : [4, 6, 1]
The occurrence count : 6

Time Complexity: O(N)
Auxiliary Space : O(N)

Approach 4: Using recursive method.


Output
The original list 1 is : [1, 3, 4, 5, 1, 4, 4, 6, 7]
The original list 2 is : [4, 6, 1]
The occurrence count : 6

Time Complexity: O(N)
Auxiliary Space : O(N)

Approach 5:Using Collections library


Output
The occurrence count : 6

Time Complexity: O(N)
Auxiliary Space : O(N)

Approach 6: Using defaultdict and sum
 


Output
The original list 1 is : [1, 3, 4, 5, 1, 4, 4, 6, 7]
The original list 2 is : [4, 6, 1]
The occurrence count : 6

Time Complexity: O(N)
Auxiliary Space : O(N)
Explanation:
We create a defaultdict of integers and store the count of each element in the first list.
Then, we use sum function to get the sum of values corresponding to the keys in the second list.
This approach is efficient as the defaultdict stores the counts in constant time and sum function runs in linear time.

Approach 7: Using List Comprehension:


Output
The original list 1 is : [1, 3, 4, 5, 1, 4, 4, 6, 7]
The original list 2 is : [4, 6, 1]
The occurrence count : 6

Time Complexity: O(N^2)
Auxiliary Space : O(1)


Practice Tags :

Explore