- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python program to get the indices of each element of one list in another list
When it is required to get the indices of each element of one list in another list, a simple iteration and the enumerate attribute along with the ‘setdefault’ method is used.
It also uses list comprehension and the ‘get’ method is used.
Example
Below is a demonstration of the same −
my_list = [14, 52, 23, 47, 18, 23, 12, 54, 43, 22, 28, 13] print("The list is :") print(my_list) my_list_2 = [17, 52, 13] print("The second list is :") print(my_list_2) element_indices = dict() for index, value in enumerate(my_list): element_indices.setdefault(value, []).append(index) my_result = [element_indices.get(index, [None]) for index in my_list_2] print("The result is :") print(my_result)
Output
The list is : [14, 52, 23, 47, 18, 23, 12, 54, 43, 22, 28, 13] The second list is : [17, 52, 13] The result is : [[None], [1], [11]]
Explanation
A list of integers is defined and is displayed on the console.
Another list of integers is defined and displayed on the console.
An empty dictionary is created.
The first list is iterated over using ‘enumerate’.
The ‘setdefault’ method is used to give a value to the element.
This is appended to the empty dictionary.
A list comprehension is used to iterate over the elements and the ‘get’ method is used to get the index values for elements in the second index.
This is stored in a list and is assigned to a variable.
This list is displayed as the output on the console.
- Related Articles
- Python Program to get indices of sign change in a list
- Python Program to find the cube of each list element
- Program to find local peak element indices from a list of numbers in Python
- Program to get indices of a list after deleting elements in ascending order in Python
- Python program to get maximum of each key Dictionary List
- Get indices of True values in a binary list in Python
- Python - First occurrence of one list in another
- Python How to get the last element of list
- Python program to remove elements at Indices in List
- Program to count number of swaps required to change one list to another in Python?
- Java Program to copy value from one list to another list
- Python - Ways to find indices of value in list
- How to get the last element of a list in Python?
- Program to find sum of concatenated pairs of all each element in a list in Python?
- Adding K to each element in a Python list of integers
