Kitchi Kitchi - 1 year ago 89
Python Question

Creating a slice object in python

If I have an array

, 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

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)

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

Question: How do I pass an index to the
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.

Answer Source

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

someseq[slice(2, None)]

is equivalent to:


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download