get many elements from a list by index in python

To get many elements from a list by index in Python, you can use indexing and slicing.

For example, if you have a list of integers my_list, and you want to get the elements at index positions 2, 4, and 6, you can do this using slicing:

main.py
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
indices = [2, 4, 6]
result = [my_list[i] for i in indices]

print(result)  # Output: [3, 5, 7]
137 chars
6 lines

In the above code, we first define my_list which contains some integers. Then we define indices which is a list of the indices of the elements we want to get from the my_list. We use a list comprehension to iterate over the indices list, and use each index to retrieve the corresponding element from my_list. Finally, the result is stored in the result list and printed to the console.

gistlibby LogSnag