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.

4
  • What are you trying to slice? Are you looking for something like stackoverflow.com/questions/2936863/… ? Commented Jun 4, 2016 at 13:24
  • Use "None" for the blank sections. So the reversing idiom [::-1] could be created with: reversing_slice=slice(None,None,-1) Commented Oct 5, 2018 at 15:24
  • 1
    @RufusVS: Why add a comment that replicates the accepted answer two years after it was posted? Commented Sep 5, 2019 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. Commented Sep 5, 2019 at 21:57

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.