- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
Find elements of a list by indices in Python
Consider two lists. The elements in the second list are numbers which needs to be considered as index position for elements of the first list. For this scenario we have the below python programs.
With map and getitem
We can use the getitem magic method is used to access the list items. We can use it along with the map function, so that we get the result from first list which takes the elements from second list as its indics.
Example
listA = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] listB = [0, 1,3] print("Given list A:",listA) print("Given list B:",listB) res=list(map(listA.__getitem__, listB)) print("Result :",res)
Output
Running the above code gives us the following result −
Given list A: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] Given list B: [0, 1, 3] Result : ['Mon', 'Tue', 'Thu']
With itemgetter
The operator module provides itemgetter method which can be used for this purpose. In the program below we expand the second list as indices and apply the itemgetter function to get the corresponding elements from the list.
Example
from operator import itemgetter listA = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] listB = [0, 1,3] print("Given list A:",listA) print("Given list B:",listB) res=list((itemgetter(*listB)(listA))) print("Result :",res)
Output
Running the above code gives us the following result −
Given list A: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] Given list B: [0, 1, 3] Result : ['Mon', 'Tue', 'Thu']
With numpy
The numpy library can achieve this by just creating an array taking the two lists as input parameters. The result is again converted into a list.
Example
import numpy as np listA = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] listB = [0, 1,3] print("Given list A:",listA) print("Given list B:",listB) res=list(np.array(listA)[listB]) print("Result :",res)
Output
Running the above code gives us the following result −
Given list A: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] Given list B: [0, 1, 3] Result : ['Mon', 'Tue', 'Thu']