Python: filtering lists by indices

You could use map

map(aList.__getitem__, myIndices)

or operator.itemgetter

f = operator.itemgetter(*aList)
f(myIndices)

Indexing by lists can be done in numpy. Convert your base list to a numpy array and then apply another list as an index:

>>> from numpy import array
>>> array(aList)[myIndices]
array(['a', 'd', 'e'], 
  dtype='|S1')

If you need, convert back to a list at the end:

>>> from numpy import array
>>> a = array(aList)[myIndices]
>>> list(a)
['a', 'd', 'e']

In some cases this solution can be more convenient than list comprehension.


Definitely use a list comprehension but here is a function that does it (there are no methods of list that do this). This is however bad use of itemgetter but just for the sake of knowledge I have posted this.

>>> from operator import itemgetter
>>> a_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> my_indices = [0, 3, 4]
>>> itemgetter(*my_indices)(a_list)
('a', 'd', 'e')

I don't know any method to do it. But you could use a list comprehension:

>>> [aList[i] for i in myIndices]