Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python List Slicing with Arbitrary Indices

Tags:

python

list

slice

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])
like image 961
Ben Hamner Avatar asked Feb 02 '12 01:02

Ben Hamner


People also ask

How do you slice a list with indices?

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 .

When slicing in Python What does the 2 in [:: 2 specify?

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).

Is Python list slicing inclusive?

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.

What is the difference between slicing and indexing of list?

“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.


3 Answers

>>> from operator import itemgetter
>>> a = range(100)
>>> itemgetter(5,13,25)(a)
(5, 13, 25)
like image 183
John La Rooy Avatar answered Oct 20 '22 08:10

John La Rooy


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.

like image 28
unutbu Avatar answered Oct 20 '22 08:10

unutbu


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]
like image 14
jsbueno Avatar answered Oct 20 '22 08:10

jsbueno