
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get match indices in Python
Two lists are given. We need to find the index of the elements from the first list whose values match with the elements in the second list.
With index
We simply design follow to get the value of the element in the second list and extract the corresponding index from the first list.
Example
listA = ['Mon','Tue', 'Wed', 'Thu', 'Fri'] listB = ['Tue', 'Fri'] # Given lists print("The given list:\n ",listA) print("The list of values:\n ",listB) # using indices res = [listA.index(i) for i in listB] # Result print("The Match indices list is : ",res)
Output
Running the above code gives us the following result −
The given list: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] The list of values: ['Tue', 'Fri'] The Match indices list is : [1, 4]
With enumerate and set
We will design a for loop which will use enumerate to extract all the elements and then match them with the key value pairs. Finally, it will extract the matching indices.
Example
listA = ['Mon','Tue', 'Wed', 'Thu', 'Fri'] listB = ['Tue', 'Fri'] # Given lists print("The given list:\n ",listA) print("The list of values:\n ",listB) # using enumerate res = [key for key, val in enumerate(listA) if val in set(listB)] # Result print("The Match indices list is : ",res)
Output
Running the above code gives us the following result −
The given list: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] The list of values: ['Tue', 'Fri'] The Match indices list is : [1, 4]
- Related Questions & Answers
- Get indices of True values in a binary list in Python
- Python Program to get indices of sign change in a list
- Program to get indices of a list after deleting elements in ascending order in Python
- DI String Match in Python
- Python program to get the indices of each element of one list in another list
- Python – Character indices Mapping in String List
- Python Indices of numbers greater than K
- Find elements of a list by indices in Python
- Python - Ways to find indices of value in list
- Program to shuffle string with given indices in Python
- Python program to remove elements at Indices in List
- Program to find indices or local peaks in Python
- Python Program to repeat elements at custom indices
- Python – Grouped Consecutive Range Indices of Elements
- Find indices with None values in given list in Python
Advertisements