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?
Asked
Active
Viewed 2,850 times
2 Answers
7
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.)
1
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]

Cory Kramer
- 114,268
- 16
- 167
- 218
-
I'm aware of this, but is there something more concise? Like PHP's [substr](http://php.net/substr) – Helen Che May 12 '15 at 14:54
-
1What could be more concise than slice notation? It is literally one line, you just give the start, then calculate the end as start+len. – Cory Kramer May 12 '15 at 14:55
-
Sorry my bad, I thought there would be something like `l[start:length]`, `length` instead of `at+size` in the standard lib. – Helen Che May 12 '15 at 14:57