Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Accessing all elements at given Python list of indexes
Sometimes we need to access multiple elements from a list at specific index positions. Python provides several efficient approaches to extract elements at given indices from a list.
Using List Comprehension
The most Pythonic approach uses list comprehension to iterate through the index list and extract corresponding elements ?
days = ["Mon", "Tue", "Wed", "Thu", "Fri"]
indices = [1, 3, 4]
# printing the lists
print("Given list: " + str(days))
print("List of indices: " + str(indices))
# use list comprehension
result = [days[i] for i in indices]
# Get the result
print("Result list: " + str(result))
The output of the above code is ?
Given list: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] List of indices: [1, 3, 4] Result list: ['Tue', 'Thu', 'Fri']
Using map() with __getitem__
The map() function with __getitem__ provides an alternative functional programming approach ?
days = ["Mon", "Tue", "Wed", "Thu", "Fri"]
indices = [1, 3, 4]
# printing the lists
print("Given list: " + str(days))
print("List of indices: " + str(indices))
# use map with __getitem__
result = list(map(days.__getitem__, indices))
# Get the result
print("Result list: " + str(result))
The output of the above code is ?
Given list: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] List of indices: [1, 3, 4] Result list: ['Tue', 'Thu', 'Fri']
Using NumPy Array Indexing
For larger datasets, NumPy provides advanced indexing capabilities ?
import numpy as np
days = ["Mon", "Tue", "Wed", "Thu", "Fri"]
indices = [1, 3, 4]
# Convert to numpy array
arr = np.array(days)
result = arr[indices]
print("Given list:", days)
print("List of indices:", indices)
print("Result list:", result.tolist())
The output of the above code is ?
Given list: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] List of indices: [1, 3, 4] Result list: ['Tue', 'Thu', 'Fri']
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| List Comprehension | High | Good | Small to medium lists |
| map() + __getitem__ | Medium | Good | Functional programming style |
| NumPy Indexing | High | Excellent | Large datasets and numerical data |
Conclusion
List comprehension is the most readable and Pythonic approach for accessing multiple list elements by indices. For large datasets, NumPy array indexing provides superior performance. Choose the method based on your data size and coding style preferences.
