
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Access All Elements at Given Python List of Indexes
We can access the individual elements of a list using the [] brackets and the index number. But when we need to access some of the indices then we cannot apply this method. We need the below approaches to tackle this.
Using two lists
In this method, along with the original list, we take the indices as another list. Then we use a for loop to iterate through the indices and supply those values to the main list for retrieving the values.
Example
given_list = ["Mon","Tue","Wed","Thu","Fri"] index_list = [1,3,4] # printing the lists print("Given list : " + str(given_list)) print("List of Indices : " + str(index_list)) # use list comprehension res = [given_list[n] for n in index_list] # Get the result print("Result list : " + str(res))
Output
Running the above code gives us the following result −
Given list : ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] List of Indices : [0, 1, 2, 3, 4] Result list : ['Tue', 'Thu', 'Fri']
Using map and geritem
Instead of using the for loop above we can also use the map as well as getitem method to get the same result.
Example
given_list = ["Mon","Tue","Wed","Thu","Fri"] index_list = [1, 3,4] # printing the lists print("Given list : " + str(given_list)) print("List of Indices : " + str(index_list)) # use list comprehension res = list(map(given_list.__getitem__,index_list)) # Get the result print("Result list : " + str(res))
Output
Running the above code gives us the following result −
Given list : ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] List of Indices : [1, 3, 4] Result list : ['Tue', 'Thu', 'Fri']
Advertisements