Open In App

Python | Accessing all elements at given list of indexes

Last Updated : 10 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Accessing an element from its index is an easier task in Python, just using the [] operator in a Python list does the trick. But in certain situations, we are presented with tasks when we have more than one index and we need to get all the elements corresponding to those indices. Let’s discuss certain ways to achieve this task.

Input: list = [9, 4, 5, 8, 10, 14]
           index_list = [1, 3, 4]
Output: 4 8 10
Explanation:The output involve the  value from the list which having the index from the index_list.

Accessing all elements at given list of indexes

Below are the methods that we will cover in this article:

Accessing all items on a given list using List Comprehension

This task is easy to perform with a loop, and hence shorthand for it is the first method to start with this task. Iterating over the index list to get the corresponding elements from the list into the new list is a brute method to perform this task. 

Python3




# initializing lists
test_list = [9, 4, 5, 8, 10, 14]
index_list = [1, 3, 4]
 
# printing original lists
print ("Original list : " + str(test_list))
print ("Original index list : " + str(index_list))
 
# using list comprehension to
# elements from list
res_list = [test_list[i] for i in index_list]
     
# printing result
print ("Resultant list : " + str(res_list))


Output :

Original list : [9, 4, 5, 8, 10, 14]
Original index list : [1, 3, 4]
Resultant list : [4, 8, 10]

Time Complexity: O(k), where k is the length of the index_list.
Space Complexity:O(k)

Accessing multiple elements at given list using map() and __getitem__ 

Yet another method to achieve this particular task is to map one list with __getitem__  and get items of indexes and get corresponding matched elements from the search list. This is quite a quick way to perform this task. 

Python3




# initializing lists
test_list = [9, 4, 5, 8, 10, 14]
index_list = [1, 3, 4]
 
# printing original lists
print("Original list : " + str(test_list))
print("Original index list : " + str(index_list))
 
# using map() + __getitem__ to
# elements from list
res_list = map(test_list.__getitem__, index_list)
 
# printing result
print("Resultant list : " + str(res_list))


Output :

Original list : [9, 4, 5, 8, 10, 14]
Original index list : [1, 3, 4]
Resultant list : [4, 8, 10]

Time Complexity: O(k), where k is the length of the index_list.
Space Complexity:O(k)

Accessing multiple items in a given list using operator.itemgetter()

This operator.itemgetter() technique is the most pythonic and elegant method to perform this particular task. This function zips the elements of the original list with the index required from the other, hence the fasted method to achieve this task. 

Python3




from operator import itemgetter
 
# initializing lists
test_list = [9, 4, 5, 8, 10, 14]
index_list = [1, 3, 4]
 
# printing original lists
print ("Original list : " + str(test_list))
print ("Original index list : " + str(index_list))
 
# using operator.itemgetter() to
# elements from list
res_list = list(itemgetter(*index_list)(test_list))
     
# printing result
print ("Resultant list : " + str(res_list))


Output :

Original list : [9, 4, 5, 8, 10, 14]
Original index list : [1, 3, 4]
Resultant list : [4, 8, 10]

Time complexity: The time complexity of this program is O(k), where k is the length of the index_list.
Space complexity: The space complexity of this program is O(k), since we are creating a new list with k elements using the itemgetter() function.

Access multiple elements in a list using numpy.take() function

Another efficient way to access multiple elements in a list at given indices is by using the numpy.take() function. Numpy is a popular library in Python used for numerical computing, and its take() function is specifically designed to perform this task.

Algorithm: Import the Numpy library then initialize the input list and index list. Use the numpy.take() function to retrieve elements from the input list at given indices.Print the original list, index list, and resultant list.

Python3




# import required libraries
import numpy as np
 
# initialize input list and index list
test_list = [9, 4, 5, 8, 10, 14]
index_list = [1, 3, 4]
 
# print original lists
print("Original list : " + str(test_list))
print("Original index list : " + str(index_list))
 
# use numpy.take() to retrieve elements
# from input list at given indices
res_list = np.take(test_list, index_list)
 
# print resultant list
print("Resultant list : " + str(res_list))


Output:

Original list : [9, 4, 5, 8, 10, 14]
Original index list : [1, 3, 4]
Resultant list : [4 8 10]

Time Complexity: The time complexity of the numpy.take() function is O(k), where k is the length of the index_list. This function is optimized for performance and is generally faster than using a loop to iterate over the index list.
Space Complexity: The space complexity of this program is O(k), as we are creating a new numpy array with k elements to store the resultant list.



Previous Article
Next Article

Similar Reads

Python | Accessing nth element from tuples in list
While working with tuples, we store different data as different tuple elements. Sometimes, there is a need to print a specific information from the tuple. For instance, a piece of code would want just names to be printed of all the student data. Lets discuss certain ways how one can achieve solutions to this problem. Method #1 : Using list comprehe
8 min read
Python Program to Accessing index and value in list
There are various methods to access the elements of a list, but sometimes we may require to access an element along with the index on which it is found. Let's see all the different ways of accessing both index and value in a list. Accessing index and value in list Using Naive method This is the most generic method that can be possibly employed to p
5 min read
Get all the information of a Collection's indexes using PyMongo
Prerequisites: MongoDB Python Basics This article is about displaying the information of Collection's indexes using the index_information() function of the PyMongo module. index_information() returns a dictionary where the keys are index names (as returned by create_index()) and the values are dictionaries containing information about each index. T
2 min read
How to rebuild all the indexes of a collection using PyMongo?
According to MongoDB documentation, normally, MongoDB compacts indexes during routine updates. For most users, the reIndex command is unnecessary. However, it may be worth running if the collection size has changed significantly or if the indexes are consuming a disproportionate amount of disk space. Prerequisites: MongoDB Python Basics This articl
2 min read
How to Drop all the indexes in a Collection using PyMongo?
Prerequisites: MongoDB and Python With the help of drop_indexes() method we can drop all the indexes in a Collection. No parameter is passed in the method. Only default index _id can not be deleted. All the Non _id indexes will be the drop by this method. It means we can only drop the index which we have created. Syntax: db.collection_name.drop_ind
2 min read
Accessing elements of a Pandas Series
Pandas Series is a one-dimensional labeled array capable of holding data of any type (integer, string, float, python objects, etc.). Labels need not be unique but must be a hashable type. An element in the series can be accessed similarly to that in an ndarray. Elements of a series can be accessed in two ways: Accessing Element from Series with Pos
6 min read
How to Create a Pivot table with multiple indexes from an excel sheet using Pandas in Python?
The term Pivot Table can be defined as the Pandas function used to create a spreadsheet-style pivot table as a DataFrame. It can be created using the pivot_table() method. Syntax: pandas.pivot_table(data, index=None) Parameters: data : DataFrame index: column, Grouper, array, or list of the previous index: It is the feature that allows you to group
2 min read
Accessing Attributes and Methods in Python
Attributes of a class are function objects that define corresponding methods of its instances. They are used to implement access controls of the classes. Attributes of a class can also be accessed using the following built-in methods and functions : getattr() - This function is used to access the attribute of object. hasattr() - This function is us
3 min read
Python | Accessing variable value from code scope
Sometimes, we just need to access a variable other than the usual way of accessing by it's name. There are many method by which a variable can be accessed from the code scope. These are by default dictionaries that are created and which keep the variable values as dictionary key-value pair. Let's talk about some of these functions. Method #1 : Usin
3 min read
Accessing Web Resources using Factory Method Design Pattern in Python
A factory is a class for building other objects, where it creates and returns an object based on the passed parameters. Here, the client provides materials to the Factory class, and the Factory class creates and returns the products based on the given material. A Factory is not a design pattern, but it serves as a basis for the Factory Method Desig
4 min read
Practice Tags :