get multiple elements from a list by index in python

To get multiple elements from a list by index in Python, we can use slicing. Slicing allows us to extract a portion of a list by specifying the start and end index values.

Here is an example of how to get multiple elements from a list by index using slicing:

main.py
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
indices = [0, 2, 4, 6]
result = [my_list[i] for i in indices]
print(result)
114 chars
5 lines

In the above example, we have a list my_list with 9 elements. We also have a list indices containing the indices of the elements we want to extract from my_list. We then use a list comprehension to iterate over the indices list and extract the corresponding elements from my_list. The result is a new list containing the elements at the specified indices.

Output:

main.py
[1, 3, 5, 7]
13 chars
2 lines

gistlibby LogSnag