Fix Python – In Python, how do I index a list with another list?

Question

Asked By – Daniel Andrén

I would like to index a list with another list like this

L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
Idx = [0, 3, 7]
T = L[ Idx ]

and T should end up being a list containing [‘a’, ‘d’, ‘h’].

Is there a better way than

T = []
for i in Idx:
    T.append(L[i])

print T
# Gives result ['a', 'd', 'h']

Now we will see solution for issue: In Python, how do I index a list with another list?


Answer

T = [L[i] for i in Idx]

This question is answered By – van

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0