Python List Slicing with Arbitrary Indices

Ben Hamner picture Ben Hamner · Feb 2, 2012 · Viewed 26.6k times · Source

Is there a better way to extract arbitrary indices from a list in python?

The method I currently use is:

a = range(100)
s = [a[i] for i in [5,13,25]]

Where a is the array I want to slice, and [5,13,25] are the elements that I want to get. It seems much more verbose than the Matlab equivalent:

a = 0:99;
s = a([6,14,26])

Answer

John La Rooy picture John La Rooy · Feb 2, 2012
>>> from operator import itemgetter
>>> a = range(100)
>>> itemgetter(5,13,25)(a)
(5, 13, 25)