66

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])
3
  • 9
    "It seems much more verbose than the Matlab". They're different languages. What did you expect? Python is less verbose than Java.
    – S.Lott
    Feb 2, 2012 at 1:53
  • Python indices are 0-based. Your 5 means the sixth element. A 1-based language would have a 6 there. How come Matlab needs 4? Does it start from -1? Feb 2, 2012 at 2:03
  • 2
    This way is actually very readable, and I like it.
    – a06e
    Feb 17, 2016 at 9:05

5 Answers 5

75
>>> from operator import itemgetter
>>> a = range(100)
>>> itemgetter(5,13,25)(a)
(5, 13, 25)
4
  • 12
    Note this edge condition if using a list as the indexes: indexes = [1,]; itemgetter(*indexes)(a) ----> returns an integer, not a tuple
    – rrauenza
    Jan 7, 2014 at 0:06
  • 2
    Thank you! With this function, it must be the first time I encounter a real need for unpack * operator.
    – pbarill
    Feb 21, 2015 at 20:34
  • 3
    Nice, I wish this were default behavior - if it's going to go to the trouble and tell me it can't accept tuple indices it might as well try and use the tuple for something first. I came here after getting used to the idea from addressing IPython cluster nodes in a similar fashion. May 19, 2015 at 15:40
  • 8
    Note what @DarrenRinger means here is that if the indices you want are in a list you would write itemgetter(*indices)(list)
    – Bar
    Oct 7, 2016 at 14:13
37

If you are a Matlab user, but want to use Python, check out numpy:

In [37]: import numpy as np

In [38]: a = np.arange(100)

In [39]: s = a[[5,13,25]]

In [40]: s
Out[40]: array([ 5, 13, 25])

Here is a comparison of NumPy and Matlab, and here is a table of common Matlab commands and their equivalents in NumPy.

14

There is no "ready made" way - the way you do it is quite ingenious, and you could use it. If you have a lot of that trough your code, you might want to use a subclass of list that would use a syntax just like matlabs - it can be done in a few lines code, the major burden is that you'd have to work always use this new class instead of the built-in lists.

class MyList(list):
    def __getitem__(self, index):
        if not isinstance(index, tuple):
            return list.__getitem__(self, index)
        return [self[i] for i in index]

And on the console:

>>> m = MyList(i * 3 for i in range(100))
>>> m[20, 25,60]
[60, 75, 180]
4

Here is a more robust version of the excellent accepted @John La Rooy answer. It passes the provided doctests. It always returns a list.

def slice_by_index(lst, indexes):
    """Slice list by positional indexes.

    Adapted from https://stackoverflow.com/a/9108109/304209.

    Args:
        lst: list to slice.
        indexes: iterable of 0-based indexes of the list positions to return.

    Returns:
        a new list containing elements of lst on positions specified by indexes.

    >>> slice_by_index([], [])
    []
    >>> slice_by_index([], [0, 1])
    []
    >>> slice_by_index(['a', 'b', 'c'], [])
    []
    >>> slice_by_index(['a', 'b', 'c'], [0, 2])
    ['a', 'c']
    >>> slice_by_index(['a', 'b', 'c'], [0, 1])
    ['a', 'b']
    >>> slice_by_index(['a', 'b', 'c'], [1])
    ['b']
    """
    if not lst or not indexes:
        return []
    slice_ = itemgetter(*indexes)(lst)
    if len(indexes) == 1:
        return [slice_]
    return list(slice_)
1

It seems like you would do:

    a = list(range(99)) 
    s = [a[5], a[13], a[25]] 

this seems to be almost identical to the matlab version.

1
  • If I had to guess, it might be because this answer does not work in Python 3 (a is not indexable). Feb 5, 2021 at 0:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.