Alex
Alex

Reputation: 12913

Combining slice objects in 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]

Upvotes: 4

Views: 516

Answers (1)

user2357112
user2357112

Reputation: 281056

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.

Upvotes: 5

Related Questions