I have a Python list, say a = [0,1,2,3,4,5,6]
. I also have a list of indices, say b = [0,2,4,5]
. How can I get the list of elements of a
You can use list comprehension to get that list:
c = [a[index] for index in b]
print c
This is equivalent to:
c= []
for index in b:
c.append(a[index])
print c
Output:
[0,2,4,5]
Note:
Remember that some_list[index]
is the notation used to access to an element of a list
in a specific index.
Yet another alternative for better performance if that is important to you- it is by no means the most Pythonic but I am pretty sure it is the most efficient:
>>> list(filter(lambda x: a.index(x) in b, a))
[0, 2, 4, 5]
Note: You do not need to convert to a list
in Python 2. However you do in Python 3 onwards (if any future visitors may have a similar issue).