Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining slice objects in python

Tags:

python

I want to extract the first 3 and last 3 items using the slice operator. Can this be done in one call by concatenating the slice objects?

a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
s1 = slice(None, 3)
s2 = slice(-3, None)
s = s1 + s2
a[s]

The above returns an error because s = s1 + s2 is not possible. Is there another way?

I'm not looking for the answer: a[s1] + a[s2]

like image 448
AlexG Avatar asked Oct 22 '25 16:10

AlexG


1 Answers

There is no object s such that a[s] would be [1, 2, 3, 7, 8, 9]. Slice objects do not support concatenation, and list.__getitem__ does not understand any object that could be used to bundle together two slices.

At some point, you will have to slice twice and combine the results. You could hide this in various ways, such as by creating a wrapper such that wrapper(a)[s1, s2] performs the two slice operations and combines the results, but you cannot delegate the job to the list.

like image 83
user2357112 supports Monica Avatar answered Oct 25 '25 06:10

user2357112 supports Monica