6

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?

Helen Che
  • 1,951
  • 5
  • 29
  • 41

2 Answers2

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.)

Community
  • 1
  • 1
chepner
  • 497,756
  • 71
  • 530
  • 681
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
  • 1
    What 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