Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a slice object in python

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.

like image 284
Kitchi Avatar asked Jun 04 '16 13:06

Kitchi


People also ask

How do you slice an object in Python?

Python slice() FunctionThe slice() function returns a slice object. A slice object is used to specify how to slice a sequence. You can specify where to start the slicing, and where to end. You can also specify the step, which allows you to e.g. slice only every other item.

Does slicing create a new object in Python?

Slicing lists does not generate copies of the objects in the list; it just copies the references to them. That is the answer to the question as asked.

Does slicing create a new object?

Note that every slice operation returns a new object. A copy of our sequence is created when using just [:] .

Can we slice set in Python?

The elements in the set are immutable(cannot be modified) but the set as a whole is mutable. There is no index attached to any element in a python set. So they do not support any indexing or slicing operation.


1 Answers

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.

like image 138
ShadowRanger Avatar answered Oct 04 '22 23:10

ShadowRanger