Open In App

Python – Accessing all elements at given list of indexes

Last Updated : 12 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, accessing elements at specific indexes in a list is a common operation. For example, you might have a list of names and want to access certain names based on their positions.

Using List Comprehension

Using List comprehension is an efficient and concise way to achieve the same result. It allows us to access the elements in a single line of code.

Python
a = [10, 20, 30, 40, 50]

# List of indexes to access
b = [1, 3, 4]

# List comprehension to access elements
result = [a[i] for i in b]

print(result)

Output
[20, 40, 50]

Other methods that we can use to access all elements at given list of indexes are:

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]

# List of indexes to access
b = [1, 3, 4]

# Using map to access elements
result = list(map(lambda i: a[i], b))
print(result)

Output
[20, 40, 50]

Using operator.itemgetter

operator.itemgetter function is useful when we need to access multiple elements at once.

Python
import operator

a = [10, 20, 30, 40, 50]

# List of indexes to access
b = [1, 3, 4]

# Using itemgetter to access elements (pass 'a' as a single argument)
getter = operator.itemgetter(*b)

# Pass the list 'a' as a single argument
result = getter(a)  
print(result)

Output
(20, 40, 50)

Using numpy for Large Lists (Fast and Efficient)

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

# List of indexes to access
b = [1, 3, 4]

# Using numpy to access elements
result = a[b]
print(result)

Output
[20 40 50]

Next Article

Similar Reads