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

 Live Demo

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

 Live Demo

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

 Live Demo

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']

Updated on: 05-May-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements