In Python, how do I index a list with a different 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 be 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'] 
+53
python list indexing
Jun 18 '09 at 11:36
source share
6 answers
 T = [L[i] for i in Idx] 
+127
Jun 18 '09 at 11:38
source share

If you use numpy, you can perform advanced slicing as follows:

 >>> 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 probably much faster (if performance is enough to worry about numpy imports)

+23
Jun 18 '09 at 12:54
source share
 T = map(lambda i: L[i], Idx) 
+5
Jun 18 '09 at 11:39
source share

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] 
+5
Jul 6 '15 at 23:12
source share

I was not happy with any of these approaches, so I came up with the Flexlist class, which allows you to flexibly index either an integer, a slice, or an 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] 

What for your example would you use as:

 L = Flexlist(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']) Idx = [0, 3, 7] T = L[ Idx ] print(T) # ['a', 'd', 'h'] 
+3
Apr 04 '15 at 2:59
source share
 L= {'a':'a','d':'d', 'h':'h'} index= ['a','d','h'] for keys in index: print(L[keys]) 

I would use Dict add desired keys to index

0
Apr 04 '15 at 15:55
source share



All Articles