How to select from list by indices in Python?
To select from a list by indices in Python, use the in operator or list comprehension.
solution 1: in operator
To select from a list by indices, use the in operator as shown below.
# select from list using in operator
myList = [1, 2, 3, 4, 5]
myIndices = [0, 2, 4]
for index in myIndices:
print(myList[index])
The in operator is used to select the values in myList by using the indices specified in myIndices.
1
3
5
solution 2: list comprehension
To select from list by indices, use list comprehension as shown below.
# select from list by indices using list comprehension
myList = [1, 2, 3, 4, 5]
myIndices = [0, 2, 4]
[print(myList[index]) for index in myIndices]
List comprehension is used, to select the values from myList by the indices specified in myIndices.
1
3
5
The same solution works for tuples, too.