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

Daniel Andrén picture Daniel Andrén · Jun 18, 2009 · Viewed 152.3k times · Source

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']

Answer

van picture van · Jun 18, 2009
T = [L[i] for i in Idx]