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


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:

print T
# Gives result ['a', 'd', 'h']
Asked By: Daniel Andrén



T = [L[i] for i in Idx]
Answered By: van
T = map(lambda i: L[i], Idx)
Answered By: mmx

If you are using numpy, you can perform extended slicing like that:

>>> import numpy
>>> a=numpy.array(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
>>> Idx = [0, 3, 7]
>>> a[Idx]
array(['a', 'd', 'h'], 

…and is probably much faster (if performance is enough of a concern to to bother with the numpy import)

Answered By: Paul

I wasn’t happy with any of these approaches, so I came up with a Flexlist class that allows for flexible indexing, either by integer, slice or index-list:

class Flexlist(list):
    def __getitem__(self, keys):
        if isinstance(keys, (int, slice)): return list.__getitem__(self, keys)
        return [self[k] for k in keys]

Which, for your example, you would use as:

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

print(T)  # ['a', 'd', 'h']
Answered By: jedwards
L= {'a':'a','d':'d', 'h':'h'}
index= ['a','d','h'] 
for keys in index:

I would use a Dict add desired keys to index

Answered By: user4749532

A functional approach:

a = [1,"A", 34, -123, "Hello", 12]
b = [0, 2, 5]

from operator import itemgetter

[1, 34, 12]
Answered By: Padraic Cunningham

You could also use the __getitem__ method combined with map like the following:

L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
Idx = [0, 3, 7]
res = list(map(L.__getitem__, Idx))
# ['a', 'd', 'h']
Answered By: David

My problem: Find indexes of list.

L = makelist() # Returns a list of different objects
La = np.array(L, dtype = object) # add dtype!
for c in chunks:
    L_ = La[c] # Since La is array, this works.
Answered By: Hunaphu
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.