Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extended slice in python?

Tags:

python

slice

I am trying to write a BitArray class, and it would be nifty to have something like numpy's array, x[i:j:k] = val.

How would I write this in Python? Not with the __setslice__, right? Because that only takes three arguments and I need one to take four.

like image 425
Broseph Avatar asked Aug 23 '12 23:08

Broseph


People also ask

What is extended slice in Python?

The slice syntax is a handy way to refer to sub-parts of sequences – typically strings and lists. The slice s[start:end] is the elements beginning at start and extending up to but not including end.

How do you slice a long string in Python?

Method 1: Using slice() method The slice() constructor creates a slice object representing the set of indices specified by range(start, stop, step). Syntax: slice(stop) slice(start, stop, step)

What does slice () do in Python?

Python slice() Function The 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.

What is range slice in Python?

Slicing range() function in Python Depending on how many arguments the user is passing to the function, the user can decide where that series of numbers will begin and end as well as how big the difference will be between one number and the next.


2 Answers

__setslice__ is deprecated - you'll want to use __setitem__ with a slice argument.

Note that, per the Python documentation, slices can only be done in the following syntactic forms: a[i:j:step], a[i:j, k:l], or a[..., i:j]. The colon-based syntax is used to define a single slice object, but as the second example shows you can have multiple slice arguments (they get passed in as a tuple of slices).

Here's an example which prints the key argument, to see its form:

>>> class Foo(object):
>>>     def __setitem__(self, key, value):
>>>         print key
>>> 
>>> a = Foo()
>>> a[1:1] = 1
slice(1, 1, None)
>>> 
>>> a[1:1:1] = 1
slice(1, 1, 1)
>>> 
>>> a[1:1, 1:1] = 1
(slice(1, 1, None), slice(1, 1, None))
like image 159
voithos Avatar answered Oct 17 '22 05:10

voithos


__setslice__ is deprecated, see the Python 3 changelog:

__getslice__(), __setslice__() and __delslice__() were killed. The syntax a[i:j] now translates to a.__getitem__(slice(i, j)) (or __setitem__() or __delitem__(), when used as an assignment or deletion target, respectively).

Similarly, you can pass a step value to slice() which means the syntax a[i:j:k] translates to a.__getitem__(slice(i, j, k)).

like image 32
Simeon Visser Avatar answered Oct 17 '22 05:10

Simeon Visser