Helen Che
Helen Che

Reputation: 2011

Python slice list at n and take the next x elements?

I've not been able to Google this issue, I want to slice [1,2,3,4,5,6] at index 2 and take the next 3 elements (ie [3,4,5]). The notation list[start:stop:step] doesn't actually allow this or am I not aware of some Pythonic way?

Upvotes: 6

Views: 3580

Answers (2)

chepner
chepner

Reputation: 531055

You could do two slices.

>>> l = [1, 2, 3, 4, 5, 6]
>>> l[start:][:length]
[3, 4, 5]

It's only 3 additional characters, although it's relatively expensive, computationally, since an extra intermediate object needs to be created for the second slice operation.

(If this were Perl, :][: could be considered a pseudo-operator.)

Upvotes: 8

Cory Kramer
Cory Kramer

Reputation: 117856

You can do this

>>> l[2:5]
[3, 4, 5]

Or more generally, if you know the start index and length of the slice

def sliceToLength(l, at, size):
    return l[at: at+size]

>>> sliceToLength(l, 2, 3)
[3, 4, 5]

Upvotes: 1

Related Questions