9

If I have an array a, I understand how to slice it in various ways. Specifically, to slice from an arbitrary first index to the end of the array I would do a[2:].

But how would I create a slice object to achieve the same thing? The two ways to create slice objects that are documented are slice(start, stop, step) and slice(stop).

So if I pass a single argument like I would in a[2:] the slice object would interpret it as the stopping index rather than the starting index.

Question: How do I pass an index to the slice object with a starting index and get a slice object that slices all the way to the end? I don't know the total size of the list.

styvane
  • 59,869
  • 19
  • 150
  • 156
Kitchi
  • 1,874
  • 4
  • 28
  • 46
  • What are you trying to slice? Are you looking for something like http://stackoverflow.com/questions/2936863/python-implementing-slicing-in-getitem ? – Jasper Jun 04 '16 at 13:24
  • Use "None" for the blank sections. So the reversing idiom [::-1] could be created with: reversing_slice=slice(None,None,-1) – RufusVS Oct 05 '18 at 15:24
  • 1
    @RufusVS: Why add a comment that replicates the accepted answer two years after it was posted? – ShadowRanger Sep 05 '19 at 16:01
  • @ShadowRanger I must have commented before reading the answers, because I see I upvoted up the accepted answer as well. I'm older and (hopefully) wiser now. – RufusVS Sep 05 '19 at 21:57

1 Answers1

19

Use None everywhere the syntax-based slice uses a blank value:

someseq[slice(2, None)]

is equivalent to:

someseq[2:]

Similarly, someseq[:10:2] can use a preconstructed slice defined with slice(None, 10, 2), etc.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271