Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Elements frequency in Tuple
Next article icon

Python - Similar index elements frequency

Last Updated : 18 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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)) 

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

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)
Auxiliary Space: O(1)

Method#5: Using Recursive method.

Algorithm:

  1. Check if the index is equal to the length of the first list. If it is, return 0.
  2. 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.
  3. If the current element in both lists is not equal, recursively call the count_matching_elements() function with the next index.
  4. Continue this process until the function has compared all the elements in the two lists.
  5. 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. 

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:
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)) 

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)
Auxiliary space: O(1)


Next Article
Python - Elements frequency in Tuple
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

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
  • Python - Similar index elements Matrix
    Sometimes, while working with data, we can have a problem in which we need to perform the construction of matrix from lists element vertically than horizontally. This kind of application can come in Data Science domains in which we need to construct Matrix from several lists. Lets discuss certain wa
    7 min read
  • Python - Group similar elements into Matrix
    Sometimes, while working with Python Matrix, we can have a problem in which we need to perform grouping of all the elements with are the same. This kind of problem can have applications in data domains. Let's discuss certain ways in which this task can be performed. Input : test_list = [1, 3, 4, 4,
    8 min read
  • Python - Group Records on Similar index elements
    Sometimes, while working with Python records, we can have a problem in which we need to perform grouping of particular index of tuple, on basis of similarity of rest of indices. This type of problems can have possible applications in Web development domain. Let's discuss certain ways in which this t
    6 min read
  • Python - List Frequency of Elements
    We are given a list we need to count frequencies of all elements in given list. For example, n = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4] we need to count frequencies so that output should be {4: 4, 3: 3, 2: 2, 1: 1}. Using collections.Countercollections.Counter class provides a dictionary-like structure that
    2 min read
  • Python - Step Frequency of elements in List
    Sometimes, while working with Python, we can have a problem in which we need to compute frequency in list. This is quite common problem and can have usecase in many domains. But we can atimes have problem in which we need incremental count of elements in list. Let's discuss certain ways in which thi
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences