Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complex list slice/index in python

Tags:

python

list

slice

I have a list that looks like this:

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

I'd like to generate a filtered list that looks like this:

filtered_lst = [2, 6, 7, 9, 10, 13]

Does Python provide a convention for custom slicing. Something such as:

lst[1, 5, 6, 8, 9, 12] # slice a list by index
like image 359
turtle Avatar asked Jan 01 '13 21:01

turtle


People also ask

What does [:- 1 mean in Python slicing?

So [::-1] means from 1st element to last element in steps of 1 in reverse order. If you have [start:stop] it's the same as step=1 .

What is slice index in Python?

Slicing is indexing syntax that extracts a portion from a list. If a is a list, then a[m:n] returns the portion of a : Starting with postion m. Up to but not including n. Negative indexing can also be used.


2 Answers

Use operator.itemgetter():

from operator import itemgetter

itemgetter(1, 5, 6, 8, 9, 12)(lst)

Demo:

>>> from operator import itemgetter
>>> lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
>>> itemgetter(1, 5, 6, 8, 9, 12)(lst)
(2, 6, 7, 9, 10, 13)

This returns a tuple; cast to a list with list(itemgetter(...)(lst)) if a that is a requirement.

Note that this is the equivalent of a slice expression (lst[start:stop]) with a set of indices instead of a range; it can not be used as a left-hand-side slice assignment (lst[start:stop] = some_iterable).

like image 157
Martijn Pieters Avatar answered Sep 18 '22 11:09

Martijn Pieters


Numpy arrays have this kind of slicing syntax:

In [45]: import numpy as np

In [46]: lst = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])

In [47]: lst[[1, 5, 6, 8, 9, 12]]
Out[47]: array([ 2,  6,  7,  9, 10, 13])
like image 42
unutbu Avatar answered Sep 18 '22 11:09

unutbu