Python - Sum of each List element occurrence in another
Last Updated :
13 Mar, 2023
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.
Python3
# Python3 code to demonstrate
# Sum of each List element occurrence in another
# using nested loops
# Initializing lists
test_list1 = [1, 3, 4, 5, 1, 4, 4, 6, 7]
test_list2 = [4, 6, 1]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Sum of each List element occurrence in another
# using nested loops
res = 0
for ele in test_list2:
for ele1 in test_list1:
if ele1 == ele:
res = res + 1
# printing result
print ("The occurrence count : " + str(res))
OutputThe 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().
Python3
# Python3 code to demonstrate
# Sum of each List element occurrence in another
# using sum() + count()
# Initializing lists
test_list1 = [1, 3, 4, 5, 1, 4, 4, 6, 7]
test_list2 = [4, 6, 1]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Sum of each List element occurrence in another
# using sum() + count()
res = sum(test_list1.count(idx) for idx in test_list2)
# printing result
print ("The occurrence count : " + str(res))
OutputThe 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
Python3
# Python3 code to demonstrate
# Sum of each List element occurrence in another
import operator as op
# Initializing lists
test_list1 = [1, 3, 4, 5, 1, 4, 4, 6, 7]
test_list2 = [4, 6, 1]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Sum of each List element occurrence in another
# using sum() + count()
res = sum(op.countOf(test_list1, idx) for idx in test_list2)
# printing result
print("The occurrence count : " + str(res))
OutputThe 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.
Python3
# Python3 code to demonstrate
# Sum of each List element occurrence in another
#using recursive approach
def occurrence_count(start,lst1,lst2,count):
if start==len(lst1): #base condition
return count
if lst1[start] in lst2: #checking if lst1[start] present in lst2 or not
count+=1
return occurrence_count(start+1,lst1,lst2,count) #calling recursive call
# initializing lists
test_list1 = [1, 3, 4, 5, 1, 4, 4, 6, 7]
test_list2 = [4, 6, 1]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
res=occurrence_count(0,test_list1,test_list2,0)
# printing result
print("The occurrence count : " + str(res))
#this code contributed by tvsk
OutputThe 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
Python3
from collections import Counter
# Initializing lists
test_list1 = [1, 3, 4, 5, 1, 4, 4, 6, 7]
test_list2 = [4, 6, 1]
# Count occurrences of elements in first list
counts = Counter(test_list1)
# Use a list comprehension to add up occurrences of elements in second list
res = sum(counts[ele] for ele in test_list2)
# printing result
print ("The occurrence count : " + str(res))
#This code is contributed Vinay Pinjala.
OutputThe occurrence count : 6
Time Complexity: O(N)
Auxiliary Space : O(N)
Approach 6: Using defaultdict and sum
Python3
from collections import defaultdict
#Function to get the sum of each element in the first list
def get_occurrence_sum(list1, list2):
dict_count = defaultdict(int)
for i in list1:
dict_count[i] += 1
return sum(dict_count[i] for i in list2)
#Initializing lists
test_list1 = [1, 3, 4, 5, 1, 4, 4, 6, 7]
test_list2 = [4, 6, 1]
#printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
#Get the sum of each element in the first list
res = get_occurrence_sum(test_list1, test_list2)
#printing result
print ("The occurrence count : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy
OutputThe 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:
Python3
# Initializing lists
test_list1 = [1, 3, 4, 5, 1, 4, 4, 6, 7]
test_list2 = [4, 6, 1]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Sum of each List element occurrence in another
# using List Comprehension
res = len([ele for ele in test_list1 if ele in test_list2])
# printing result
print ("The occurrence count : " + str(res))
#This code is contributed by Jyothi pinjala
OutputThe 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)
Similar Reads
Python | Count occurrence of all elements of list in a tuple
Given a tuple and a list as input, write a Python program to count the occurrences of all items of the list in the tuple. Examples: Input : tuple = ('a', 'a', 'c', 'b', 'd') list = ['a', 'b'] Output : 3 Input : tuple = (1, 2, 3, 1, 4, 6, 7, 1, 4) list = [1, 4, 7] Output : 6 Approach #1 : Naive Appro
5 min read
Element Occurrence in Dictionary of List Values - Python
We are having a dictionary of list we need to find occurrence of all elements. For example, d = {'a': [1, 2, 3, 1], 'b': [3, 4, 1], 'c': [1, 5, 6]} we need to count the occurrence of all elements in dictionary list so that resultant output should be {'a': 2, 'b': 1, 'c': 1}.Using a Dictionary Compre
3 min read
Python - Occurrence counter in List of Records
Sometimes, while dealing with records we can have a problem in which we need count the occurrence of incoming digits corresponding to different characters/players in a game and compile them in a dictionary. This can have application in gaming and web development. Lets discuss a way in which this can
2 min read
Get the indices of all occurrences of an element in a list - Python
We are given a list and our task is to find all the indices where a particular element occurs. For example, if we have a list like [1, 2, 3, 2, 4, 2] and the element is 2, then the output will be [1, 3, 5] because 2 appears at these positions.Using List ComprehensionList comprehension allows for a c
2 min read
Python - Operation to each element in list
Given a list, there are often when performing a specific operation on each element is necessary. While using loops is a straightforward approach, Python provides several concise and efficient methods to achieve this. In this article, we will explore different operations for each element in the list.
2 min read
Python | Count tuples occurrence in list of tuples
Many a time while developing web and desktop products in Python, we use nested lists and have several queries about how to find the count of unique tuples. Let us see how to get the count of unique tuples in the given list of tuples. Below are some ways to achieve the above task. Method #1: Using It
5 min read
Python | Alternate element summation in list
The problem of getting summation of a list is quite generic and we might some day face the issue of getting the summation of alternate elements and get the list of 2 elements containing summation of alternate elements. Let's discuss certain ways in which this can be performed. Method #1 : Using list
5 min read
Python Check if the List Contains Elements of another List
The task of checking if a list contains elements of another list in Python involves verifying whether all elements from one list are present in another list. For example, checking if ["a", "b"] exists within ["a", "b", "c", "d"] would return True, while checking ["x", "y"] would return False. Using
3 min read
Python - Sum of different length Lists of list
Getting the sum of list is quite common problem and has been dealt with and discussed many times, but sometimes, we require to better it and total sum, i.e. including those of nested list as well. Letâs try and get the total sum and solve this particular problem. Method #1 : Using list comprehension
5 min read
Add Elements of Two Lists in Python
Adding corresponding elements of two lists can be useful in various situations such as processing sensor data, combining multiple sets of results, or performing element-wise operations in scientific computing. List Comprehension allows us to perform the addition in one line of code. It provides us a
3 min read