Accessing all elements at given Python list of indexes

PythonServer Side ProgrammingProgramming

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

 Live Demo

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

 Live Demo

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']
raja
Published on 03-Mar-2020 05:28:26
Advertisements