Python - Similar index elements frequency
Last Updated :
18 Apr, 2023
Sometimes, while working with Python list, we can have a problem in which we need to check if one element has similar index occurrence in other list. This can have possible application in many domains. Lets discuss certain ways in which this task can be performed.
Method #1 : Using sum() + zip() The combination of above functions can be used to perform this task. In this, we perform summation of elements that after zipping cross lists together match.
Python3
# Python3 code to demonstrate
# Similar index elements frequency
# using sum() + zip()
# Initializing lists
test_list1 = [1, 3, 5, 6, 8]
test_list2 = [4, 3, 6, 6, 10]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Similar index elements frequency
# using sum() + zip()
res = sum(x == y for x, y in zip(test_list1, test_list2))
# printing result
print ("Number of elements having similar index : " + str(res))
Output : The original list 1 is : [1, 3, 5, 6, 8]
The original list 2 is : [4, 3, 6, 6, 10]
Number of elements having similar index : 2
Time Complexity: O(n*n) where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n), where n is the number of elements in the new res list
Method #2 : Using list comprehension + enumerate() The combination of above functionalities can be used to perform this task. In this, we iterate through each element in lists and increase the sum accordingly.
Python3
# Python3 code to demonstrate
# Similar index elements frequency
# using list comprehension + enumerate()
# Initializing lists
test_list1 = [1, 3, 5, 6, 8]
test_list2 = [4, 3, 6, 6, 10]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Similar index elements frequency
# using list comprehension + enumerate()
res = len([key for key, val in enumerate(zip(test_list1, test_list2)) if val[0] == val[1]])
# printing result
print ("Number of elements having similar index : " + str(res))
Output : The original list 1 is : [1, 3, 5, 6, 8]
The original list 2 is : [4, 3, 6, 6, 10]
Number of elements having similar index : 2
Method #3 : Using map() + itertools zip_longest()
Python3
#Python3 code to demonstrate
#Similar index elements frequency
#using map() + zip_longest()
#importing itertools module
from itertools import zip_longest
#Initializing lists
test_list1 = [1, 3, 5, 6, 8]
test_list2 = [4, 3, 6, 6, 10]
#printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
#Similar index elements frequency
#using map() + zip_longest()
res = sum(map(lambda x: x[0] == x[1], zip_longest(test_list1, test_list2, fillvalue=-1)))
#printing result
print ("Number of elements having similar index : " + str(res))
OutputThe original list 1 is : [1, 3, 5, 6, 8]
The original list 2 is : [4, 3, 6, 6, 10]
Number of elements having similar index : 2
Time Complexity: O(n) where n is the length of the longest list.
Auxiliary Space: O(1) as we are only using a single integer to store the result.
In this approach, we first import the zip_longest() method from itertools module and then use the map() function to apply a lambda function that compares elements at each index of both the lists and then we use the sum() method to find the sum of all comparisons (True or False). The fillvalue argument in zip_longest is used to fill values in the shorter list if they are less elements than the longer list, so that they can be compared.
This approach gives us a concise way to find the number of elements with the same index in both the lists and its time complexity is O(n) where n is the length of the longest list and its space complexity is O(1) as we are only using a single integer to store the result.
Method #4: Using for loop
Python3
# Initializing lists
test_list1 = [1, 3, 5, 6, 8]
test_list2 = [4, 3, 6, 6, 10]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Using for loop
count = 0
for i in range(len(test_list1)):
if test_list1[i] == test_list2[i]:
count += 1
# printing result
print("Number of elements having similar index : " + str(count))
#This code is contributed by Vinay Pinjala.
OutputThe original list 1 is : [1, 3, 5, 6, 8]
The original list 2 is : [4, 3, 6, 6, 10]
Number of elements having similar index : 2
Time Complexity: O(n)
Auxiliary Space: O(1)
Method#5: Using Recursive method.
Algorithm:
- Check if the index is equal to the length of the first list. If it is, return 0.
- Check if the current element in both lists is equal. If it is, recursively call the count_matching_elements() function with the next index and add 1 to the result.
- If the current element in both lists is not equal, recursively call the count_matching_elements() function with the next index.
- Continue this process until the function has compared all the elements in the two lists.
- Return the number of elements that have the same index and are equal in both lists.
Python3
def count_matching_elements(list1, list2, index=0):
if index == len(list1):
return 0
elif list1[index] == list2[index]:
return 1 + count_matching_elements(list1, list2, index + 1)
else:
return count_matching_elements(list1, list2, index + 1)
# Initializing lists
test_list1 = [1, 3, 5, 6, 8]
test_list2 = [4, 3, 6, 6, 10]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Using recursive method
count = count_matching_elements(test_list1,test_list2)
# printing result
print("Number of elements having similar index : " + str(count))
#This code is contributed by tvsk.
OutputThe original list 1 is : [1, 3, 5, 6, 8]
The original list 2 is : [4, 3, 6, 6, 10]
Number of elements having similar index : 2
Time complexity:
The time complexity of the function is O(n), where n is the length of the input lists. This is because the function needs to compare each element in the two lists once. Since the function visits each element once, the time complexity is linear in the length of the input.
Auxiliary space:
The auxiliary space complexity of the function is O(n), where n is the maximum depth of the recursion. This is because the function creates a new stack frame for each recursive call. The maximum depth of the recursion is equal to the length of the input lists. Therefore, the space complexity of the function is also linear in the length of the input.
Method 6: Using the built-in function 'filter' and 'lambda'
Step-by-step approach:
- Define a lambda function to check if the elements at the same index in both lists are equal. The lambda function should take two arguments (x and y) and return True if they are equal and False otherwise.
- Use the built-in function 'filter' to filter the list of tuples obtained by applying the lambda function to the zipped lists.
- Get the length of the resulting filtered list using the built-in function 'len' and store it in a variable 'count'.
- Return 'count'.
Below is the implementation of the above approach:
Python3
def count_matching_elements(list1, list2):
count = len(list(filter(lambda x: x[0] == x[1], zip(list1, list2))))
return count
# Initializing lists
test_list1 = [1, 3, 5, 6, 8]
test_list2 = [4, 3, 6, 6, 10]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Using filter and lambda function
count = count_matching_elements(test_list1,test_list2)
# printing result
print("Number of elements having similar index : " + str(count))
OutputThe original list 1 is : [1, 3, 5, 6, 8]
The original list 2 is : [4, 3, 6, 6, 10]
Number of elements having similar index : 2
Time complexity: O(n)
Auxiliary space: O(1)
Similar Reads
Python | Extract similar index elements Sometimes, while working with Python data, we can have a problem in which we require to extract the values across multiple lists which are having similar index values. This kind of problem can come in many domains. Let's discuss certain ways in which this problem can be solved. Method #1 : Using loo
6 min read
Python - Elements frequency in Tuple Given a Tuple, find the frequency of each element. Input : test_tup = (4, 5, 4, 5, 6, 6, 5) Output : {4: 2, 5: 3, 6: 2} Explanation : Frequency of 4 is 2 and so on.. Input : test_tup = (4, 5, 4, 5, 6, 6, 6) Output : {4: 2, 5: 2, 6: 3} Explanation : Frequency of 4 is 2 and so on.. Method #1 Using def
7 min read
Python - Similar Consecutive elements frequency Sometimes, while working with Python, we can have a problem in which we have to find the occurrences of elements that are present consecutively. This problem have usage in school programming and data engineering. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop
5 min read
Python - Elements frequency in Tuple Matrix Sometimes, while working with Python Tuple Matrix, we can have a problem in which we need to get the frequency of each element in it. This kind of problem can occur in domains such as day-day programming and web development domains. Let's discuss certain ways in which this problem can be solved. Inp
5 min read
Sort List Elements by Frequency - Python Our task is to sort the list based on the frequency of each element. In this sorting process, elements that appear more frequently will be placed before those with lower frequency. For example, if we have: a = ["Aryan", "Harsh", "Aryan", "Kunal", "Harsh", "Aryan"] then the output should be: ['Aryan'
3 min read