Open In App

Accessing all elements at given list of indexes-Python

Last Updated : 28 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Sometimes, you may have a list of data and a separate list of indexes and the goal is to extract only the elements at those specific positions. For example, given a list [10, 20, 30, 40, 50] and a list of indexes [1, 3, 4], you want to retrieve [20, 40, 50] the values at those index positions in the original list. Let’s explore different methods to do this efficiently.

Using List Comprehension

List comprehension is a clean way to extract elements from a list. It's great for short, readable and efficient code when you're working with small to medium datasets.

Python
a = [10, 20, 30, 40, 50]
b = [1, 3, 4]

res = [a[i] for i in b]
print(res)

Output
[20, 40, 50]

Explanation: [a[i] for i in b] retrieves elements from list a at the indexes specified in list b and stores them in res.

Using map Function

map function is another way to access elements at specific indexes. It applies a function to every item in the list of indexes and gives us the result as a list.

Python
a = [10, 20, 30, 40, 50]
b = [1, 3, 4] 

res = list(map(lambda i: a[i], b))
print(res)

Output
[20, 40, 50]

Explanation: map() function with lambda i: a[i] retrieves elements from list a at the indexes specified in list b and stores them in res.

Using operator.itemgetter

itemgetter() is a neat way from Python’s operator module to fetch multiple elements at once by index. It returns a function that grabs the elements you specify.

Python
import operator
a = [10, 20, 30, 40, 50]
b = [1, 3, 4] 
getter = operator.itemgetter(*b)

res = getter(a)  
print(res)

Output
(20, 40, 50)

Explanation: operator.itemgetter(*b) creates a function to fetch elements from a at indexes in b and getter(a) returns them as a tuple in res.

Using numpy

If we are dealing with large lists or arrays, we can use the numpy library for fast indexing. numpy is designed for numerical computing and can handle large datasets much more efficiently than regular Python lists.

Python
import numpy as np

a = np.array([10, 20, 30, 40, 50])
b = [1, 3, 4] 

res = a[b]
print(res)

Output
[20 40 50]

Explanation: a[b] directly retrieves elements from array a at the indexes in list b and stores them in res as a NumPy array.


Next Article

Similar Reads