The Wayback Machine - https://web.archive.org/web/20241119235038/https://www.geeksforgeeks.org/python-accessing-all-elements-at-given-list-of-indexes/
Open In App

Python | Accessing all elements at given list of indexes

Last Updated : 10 Aug, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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
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
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
Accessing Data Along Multiple Dimensions Arrays in Python Numpy
NumPy (Numerical Python) is a Python library that comprises of multidimensional arrays and numerous functions to perform various mathematical and logical operations on them. NumPy also consists of various functions to perform linear algebra operations and generate random numbers. NumPy is often used along with packages like SciPy and Matplotlib for
3 min read
How to use Hierarchical Indexes with Pandas ?
The index is like an address, that’s how any data point across the data frame or series can be accessed. Rows and columns both have indexes, rows indices are called index and for columns, it's general column names. Hierarchical Indexes Hierarchical Indexes are also known as multi-indexing is setting more than one column name as the index. In this a
3 min read
Change column names and row indexes in Pandas DataFrame
Given a Pandas DataFrame, let's see how to change its column names and row indexes. About Pandas DataFramePandas DataFrame are rectangular grids which are used to store data. It is easy to visualize and work with data when stored in dataFrame. It consists of rows and columns.Each row is a measurement of some instance while column is a vector which
4 min read
Using Timedelta and Period to create DateTime based indexes in Pandas
Real life data often consists of date and time-based records. From weather data to measuring some other metrics in big organizations they often rely on associating the observed data with some timestamp for evaluating the performance over time. We have already discussed how to manipulate date and time in pandas, now let's see the concepts of Timesta
3 min read
Setting and accessing name of a Label - PyQt5
In this article we will see how we can set and access the description of the label. A label is a graphical control element which displays text on a form. It is usually a static control; having no interactivity. A label is generally used to identify a nearby text box or other widget. Description of label is the details of the label, setting descript
2 min read
PyQt5 – Setting and accessing name of a Label
While designing a Gui (Graphical User Interface) application, we mostly end up making lots of labels. For back-end coders, it become tough to distinguish between the label. To overcome this situation, need of settings label name is required, for examples among hundreds of label we can distinguish them by setting their names like some are "info" lab
2 min read
PyQt5 – Setting and accessing description of a Status Bar
In this article, we will see how to set and access the description of the Status Bar. In order to set description we use statusBar().setAccessibleDescription() method and for accessing we use self.statusBar().accessibleDescription() method. Description of Status Bar is the details of the Status Bar and setting description helps in better understand
2 min read
PyQt5 – Setting and accessing name of a Status Bar
While designing a Gui (Graphical User Interface) application, we mostly end up making lots of windows with each having status bar. For back-end coders it become tough to distinguish between the windows status bar. To overcome this need of settings name required, for examples among hundreds of status bar we can distinguish them by setting their name
2 min read
PyQt5 – Setting and accessing WHATS THIS help text for Status Bar
n PyQt5 there are lots of widgets and bars and when we tend to make an application, we end up putting lots of windows and for each window there exit status bar. Sometimes we can't remember why this status bar is used and what is this status bar. That’s why for back-end purposes PyQt5 allows us to set help text. In this article we will see how to se
2 min read
PyQt5 - Setting and accessing name of Radio button
In this article we will see how we can set and access the name of the radio button. Name is basically used to distinguish the radio buttons because when we create GUI (Graphical User Interface) we make lot of radio button and there is a need to distinguish them as some radio button will be for choosing filter some will be for selecting color etc th
2 min read
PyQt5 - Accessing Radio button tooltip content
In this article we will see how we can access the tool tip content of the radio button. Tool tip is basically a message appear when we hover mouse over the radio button. Tool tip gives the tip and help the user to understand better about the radio button. In order to access the content of radio button tool tip we will use toolTip method Syntax : ra
2 min read
PyQt5 - Accessing role of item in ComboBox
In this article we will see how we can access the item role in combo box. By default when we create a combo box and add items to it no role is set to the items. In order to set the role we use setItemData method and in order to access the role we use itemData method. Syntax : combo_box.temData(index) Argument : It takes integer as argument Return :
2 min read
PyQt5 – Accessing name of ComboBox
In this article we will see how we can access name of the combo box. Name is basically used to distinguish combo boxes with each other, programmer can name the combo box according to its use so that they can be easily distinguishable. By default no name is given to the combo box. In order to set the name we use setAccessibleName method. In order to
2 min read
PyQt5 - Accessing tool tip of the Combo Box
In this article we will see how we can access the tool tip of the combo box, tool tip is basically a tip occur when mouse hover over the combo box widget. In order to set the tool tip to the combo box we use setToolTip method. Note : Tool tip get only visible when mouse hover over the combo box not on the drop down view In order to access the tool
2 min read
PyQt5 - Accessing help text of the combo box
In this article we will see how we can access help text to the combo box. Help text is basically used to tell the programmer about the emergency information like reference links etc, programmer set help text to the combo box so that when some other programmer get difficulty in understanding the combo box, he/she can take help from the help text. In
2 min read
PyQt5 - Accessing tool tip duration of the Combo Box
In this article we will see how we can access the tool tip duration to the combo box. Tool tip is basically a tip occur when mouse hover over the combo box widget. In order to set the tool tip to the combo box we use setToolTip method. In order to set the tool tip duration we use setToolTipDuration method. Note : Tool tip get only visible when mous
2 min read
PyQt5 QSpinBox - Accessing Maximum value
In this article we will see how we can get the maximum value i.e upper bound of the spin box, by default when we create a spin box it ranges from 0 to 99 i.e its maximum value is 99 although we can change this. In order to do this we will use spin_box.maximum method Syntax : spin_box.maximum() Argument : It takes no argument Return : It returns int
2 min read
PyQt5 QSpinBox - Accessing Suffix
In this article we will see how we can access the suffix of the spin box, suffix is the extra text added at the end of the value, it is non editable and permanent. By default there is no suffix set to the spin box although we can set suffix any time with the help of setSuffix method. In order to do this we will use suffix method. Syntax : spin_box.
2 min read
PyQt5 QSpinBox - Accessing Prefix
In this article we will see how we can access the prefix of the spin box, prefix is basically the text which is inserted before the value of spin box, prefix remain constant for each value of spin box i.e it is not editable. By default no prefix is set to the spin box we use setPrefix method to set the prefix. In order to access the prefix we will
2 min read
PyQt5 QSpinBox - Accessing single step size
In this article we will see how we can access the single step size of the spin box, by default when we create a spin box it step size is 1. Step size is basically the incremental or decrement size. In order to set the step size we use setSingleStep method. In order to do this we will use singleStep method. Syntax : spin_box.singleStep() Argument :
2 min read
PyQt5 QSpinBox - Accessing step type
In this article we will see how we can access the step type of the spin box, there are two types of step types i.e default one which increment value normally and other is adaptive decimal. In order to do this we will use stepType method Note : This feature was introduced in Qt 5.12. so lower versions don't have this feature. Syntax : spin_box.stepT
2 min read
PyQt5 Label - Accessing blur radius to shadow
In this article we will see how we can access the blur radius of the shadow of the label. The blur radius, if set to 0 the shadow will be sharp, the higher the number, the more blurred it will be, by default the blur radius is 0, we use setBlurRadius method to set the blur radius In order to access the blur radius of the shadow of label we use blur
2 min read
Practice Tags :
three90RightbarBannerImg