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])
To extract elements with specific indices from a Python list, use slicing list[start:stop:step] . If you cannot use slicing because there's no pattern in the indices you want to access, use the list comprehension statement [lst[i] for i in indices] , assuming your indices are stored in the variable indices .
Second note, when no start is defined as in A[:2] , it defaults to 0. There are two ends to the list: the beginning where index=0 (the first element) and the end where index=highest value (the last element).
Python is a zero-indexed language (things start counting from zero), and is also left inclusive, right exclusive you are when specifying a range of values. This applies to objects like lists and Series , where the first element has a position (index) of 0.
“Indexing” means referring to an element of an iterable by its position within the iterable. “Slicing” means getting a subset of elements from an iterable based on their indices.
>>> from operator import itemgetter
>>> a = range(100)
>>> itemgetter(5,13,25)(a)
(5, 13, 25)
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With