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 | 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 - 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
Find Sum and Average of List in Python Our goal is to find sum and average of List in Python. The simplest way to do is by using a built-in method sum() and len(). For example, list of numbers is, [10, 20, 30, 40, 50] the sum is the total of all these numbers and the average is the sum divided by the number of elements in the list.Using
2 min read
Count Occurance of Substring in a List of Strings - Python To count the occurrences of a particular substring in a list of strings in Python, we can use several methods. In this article, we are going to explore different methods to count the existence of a particular substring in a given list.Using sum() and Generator ExpressionThis method uses a generator
2 min read
Python | Add the occurrence of each number as sublists Given a list of numbers, the task is to count the occurrence of each element and add as sublists. Examples: Input: l1 = [3, 5, 7, 2, 3, 5, 9.1] Output: [[3, 2], [5, 2], [7, 1], [2, 1], [9.1, 1]] Input: l1 = [1, 1, 2, 2, 3, 1] Output: [[1, 3], [2, 2], [3, 1]] Note: Format output 2d list is [['item1',
3 min read
Sum of number digits in List in Python Our goal is to calculate the sum of digits for each number in a list in Python. This can be done by iterating through each number, converting it to a string, and summing its digits individually. We can achieve this using Pythonâs built-in functions like sum(), map(), and list comprehensions. For exa
2 min read
Python | Record elements Average in List Given a list of tuples, write a program to find average of similar tuples in list. Examples: Input: [('Geeks', 10), ('For', 10), ('Geeks', 2), ('For', 9), ('Geeks', 10)] Output: Resultant list of tuples: [('For', 9.5), ('Geeks', 7.333333333333333)] Input: [('Akshat', 10), ('Garg', 10), ('Akshat', 2)
3 min read