

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Accessing 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']
- Related Questions & Answers
- Print nodes of linked list at given indexes in C language
- Program to return number of smaller elements at right of the given list in Python
- Python - Ways to format elements of given list
- Python Program that print elements common at specified index of list elements
- Number of indexes with equal elements in given range in C++
- List consisting of all the alternate elements in Python
- Accessing elements of a Pandas Series
- Python – Rows with all List elements
- Get positive elements from given list of lists in Python
- Python program to remove elements at Indices in List
- Python – Test for all Even elements in the List for the given Range
- Find all elements count in list in Python
- Python – Strings with all given List characters
- Find sum of frequency of given elements in the list in Python
- Count occurrence of all elements of list in a tuple in Python
Advertisements