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 - Matrix elements Frequencies Counter
Next article icon

Python | Matching elements count

Last Updated : 10 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Sometimes, while working with lists we need to handle two lists and search for the matches, and return just the count of indices of the match. Querying whole list for the this process is not feasible when the size of master list is very large, hence having just the match indices helps in this cause. Let’s discuss certain ways in which this can be achieved. 

Method #1 : Using list comprehension + index() + len() This problem can potentially be solved using the index function of python to get the wanted indices and list comprehension can be used to extend this to the whole string. The len() is used to return total count of match. 

Python3




# Python3 code to demonstrate
# Matching elements count
# using list comprehension and index() + len()
 
# initializing lists
test_list1 = [5, 4, 1, 3, 2]
test_list2 = [1, 2]
 
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
 
# using list comprehension and index() + len()
# Matching elements count
res = len([test_list1.index(i) for i in test_list2])
 
# print result
print("The Match indices list count is : " + str(res))
 
 
Output
The original list 1 : [5, 4, 1, 3, 2] The original list 2 : [1, 2] The Match indices list count is : 2

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

Method #2 : Using enumerate() + len() + list comprehension The enumerate function can be used to produce the key value pair for the list being it’s index and value and we can store them using list comprehension. The len() is used to return total count of match. 

Python3




# Python3 code to demonstrate
# Matching elements count
# using list comprehension and enumerate() + len()
 
# initializing lists
test_list1 = [5, 4, 1, 3, 2]
test_list2 = [1, 2]
 
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
 
# using list comprehension and enumerate() + len()
# Matching elements count
res = len([key for key, val in enumerate(test_list1) if val in set(test_list2)])
 
# print result
print("The Match indices list count is : " + str(res))
 
 
Output
The original list 1 : [5, 4, 1, 3, 2] The original list 2 : [1, 2] The Match indices list count is : 2

Time Complexity: O(n) where n is the number of elements in the in the list “test_list”. The enumerate() + len() + list comprehension is used to perform the task and it takes O(n) time.
Auxiliary Space: O(1) constant additional space is needed

Method #3:Using Counter() function

Python3




# Python3 code to demonstrate
# Matching elements count
from collections import Counter
res = 0
# initializing lists
test_list1 = [5, 4, 1, 3, 2]
test_list2 = [1, 2]
 
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
 
freq = Counter(test_list1)
for i in test_list2:
    if i in freq.keys():
        res += 1
# print result
print("The Match indices list count is : " + str(res))
 
 
Output
The original list 1 : [5, 4, 1, 3, 2] The original list 2 : [1, 2] The Match indices list count is : 2

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

Method #4: Using set intersection

Python3




# Python3 code to demonstrate
# Matching elements count
# using set intersection
 
# initializing lists
test_list1 = [5, 4, 1, 3, 2]
test_list2 = [1, 2]
 
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
 
# using set intersection
# Matching elements count
res = len(set(test_list1) & set(test_list2))
 
# print result
print("The Match indices list count is : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy
 
 
Output
The original list 1 : [5, 4, 1, 3, 2] The original list 2 : [1, 2] The Match indices list count is : 2

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

This approach uses the set intersection method to find the common elements between the two lists. The intersection of two sets returns a new set containing only the elements present in both sets. The length of this new set is the count of common elements between the two lists.

Method #5: Using a dictionary and a loop

  • Initialize an empty dictionary.
  • Loop through the first list and add each element as a key to the dictionary with a value of 1.
  • Loop through the second list and check if each element is a key in the dictionary.
  • If it is, increment the value of the corresponding key in the dictionary by 1.
  • The count of matching elements is the sum of the values in the dictionary that are greater than or equal to 1.
  • Return the count.

Python3




# Python3 code to demonstrate
# Matching elements count
# using a dictionary and a loop
 
# initializing lists
test_list1 = [5, 4, 1, 3, 2]
test_list2 = [1, 2]
 
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
 
# using a dictionary and a loop
# Matching elements count
dict1 = {}
for num in test_list1:
    dict1[num] = 1
count = 0
for num in test_list2:
    if num in dict1:
        dict1[num] += 1
for val in dict1.values():
    if val >= 2:
        count += 1
 
# print result
print("The Match indices list count is : " + str(count))
 
 
Output
The original list 1 : [5, 4, 1, 3, 2] The original list 2 : [1, 2] The Match indices list count is : 2

Time complexity: O(n+m), where n and m are the lengths of the two lists, since we loop through each list once.
Auxiliary space: O(n), where n is the length of the first list, since we store each element of the first list as a key in the dictionary.



Next Article
Python - Matrix elements Frequencies Counter
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python | Count of Matching i, j index elements
    Sometimes, while programming, we can have a problem in which we need to check for ith and jth character of each string. We may require to extract count of all strings with similar ith and jth characters. Let’s discuss certain ways in which this task can be performed. Method #1 : Using loop This is b
    4 min read
  • Python - Count elements in tuple list
    Sometimes, while working with data in form of records, we can have a problem in which we need to find the count of all the records received. This is a very common application that can occur in Data Science domain. Let’s discuss certain ways in which this task can be performed. Method #1: Using len()
    5 min read
  • Python | Counting Nth tuple element
    Sometimes, while working with Python, we can have a problem in which we need to count the occurrence of a particular's elements. This kind of problem is quite common while working with records. Let's discuss a way in which this task can be performed. Method #1 : Using Counter() + generator expressio
    5 min read
  • Python - Count elements in record tuple
    Sometimes, while working with data in form of records, we can have a problem in which we need to find the total element counts of all the records received. This is a very common application that can occur in Data Science domain. Let’s discuss certain ways in which this task can be performed. Method
    5 min read
  • Python - Matrix elements Frequencies Counter
    Sometimes, while working with python Matrix, we can have a problem in which we need to find frequencies of all elements in Matrix. This kind of problem can have application in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using Counter() + sum() + map() The
    5 min read
  • Python | Count unmatched elements
    Checking a number/element by a condition is a common problem one faces and is done in almost every program. Sometimes we also require to get the totals number that does not match the particular condition to have a distinguish which match for further utilization. Lets discuss certain ways in which th
    4 min read
  • Python | List Element Count with Order
    Sometimes, while working with lists or numbers we can have a problem in which we need to attach with each element of list, a number, which is the position of that element's occurrence in that list. This type of problem can come across many domains. Let's discuss a way in which this problem can be so
    4 min read
  • Operations on Python Counter
    The counter can be used to calculate the frequency in a list or in a string because as any list or string is passed as input, it returns output as a dictionary having keys are the unique elements of the list and values are the corresponding frequencies of the elements. In the code given below, Count
    4 min read
  • Python - Consecutive identical elements count
    Given the elements list, get all the elements that have an identical element as the next element. Input : test_list = [4, 5, 5, 5, 5, 6, 6, 7, 8, 2, 2, 10] Output : 3 Explanation : 5, 6 and 2 has identical element as their next element. Input : test_list = [4, 5, 5, 5, 5, 6, 6, 7, 8, 2, 3, 10] Outpu
    5 min read
  • Search Elements in a Matrix - Python
    The task of searching for elements in a matrix in Python involves checking if a specific value exists within a 2D list or array. The goal is to efficiently determine whether the desired element is present in any row or column of the matrix. For example, given a matrix a = [[4, 5, 6], [10, 2, 13], [1
    3 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