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

## Question:

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

``````T = [L[i] for i in Idx]
``````
``````T = map(lambda i: L[i], Idx)
``````

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'],
dtype='|S1')
``````

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

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']
``````
``````L= {'a':'a','d':'d', 'h':'h'}
index= ['a','d','h']
for keys in index:
print(L[keys])
``````

I would use a `Dict add` desired `keys` to `index`

A functional approach:

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

from operator import itemgetter

print(list(itemgetter(*b)(a)))
[1, 34, 12]
``````

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))
print(res)
# ['a', 'd', 'h']
``````

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.
``````
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.