get list elements using a list of indices in python

You can use indexing to access the elements of a list in python. If you have a list of indices, you can get the elements corresponding to those indices using list comprehension. Here's an example:

main.py
my_list = ['apple', 'banana', 'cherry', 'durian', 'eggfruit']
indices = [0, 2, 4]
output_list = [my_list[i] for i in indices]
print(output_list)
145 chars
5 lines

Output:

main.py
['apple', 'cherry', 'eggfruit']
32 chars
2 lines

Here, we have a list my_list and a list of indices indices. We use list comprehension to create a new list output_list which contains the elements of my_list at the indices specified in indices. The output is ['apple', 'cherry', 'eggfruit'].

gistlibby LogSnag