Use a variable to describe an index range/slice for array / list indexing

I want to use a use a name to refer to an index range for array/list indexing. Plus, I want to be able to do arithmetic on it. For instance, I want to do

myrange = 3:10
myrange2 = myrange + 5
arr2[myrange2] = arr1[myrange]  # This being equivalent to arr2[8:15] = arr1[3:10] 
myrange3 = myrange * 2 + 5
arr2[myrange3] = arr1[myrange]  # This being equivalent to arr2[11:25] = arr1[3:10] 

Is this possible with python lists and numpy arrays?

Upvotes: 1

Views: 172

Answers (2)

norok2
norok2

Reputation: 26886

You can simply use a slice():

myrange = slice(3, 10)
myrange2 = slice(3 + 5, 10 + 5)
arr2[myrange2] = arr1[myrange]

This can be made into a function easily:

def add_to_slice(slice_, offset):
    return slice(slice_.start + offset, slice_.stop + offset)


myrange = slice(3, 10)
myrange2 = add_to_slice(myrange, 5)
arr2[myrange2] = arr1[myrange]

If you want to use + you would need to patch the slice class (since slice is not an acceptable base class) to include a __add__ method, i.e.:

class Slice(slice):
    pass

TypeError: type 'slice' is not an acceptable base type


EDIT

A "perhaps close enough" approach would be wrap a slice around another class, say Slice and, optionally, make it easy to access the inner slice, e.g.:

class Slice(object):
    def __init__(self, *args):
        self.slice_ = slice(*args)

    def __call__(self):
        return self.slice_

    def __add__(self, offset):
        return Slice(self.slice_.start + offset, self.slice_.stop + offset, self.slice_.step)


myrange = Slice(2, 5)
myrange2 = myrange + 3

mylist = list(range(100))
print(mylist[myrange()])
print(mylist[myrange2()])

(You may want to refine the code for production to handle the possibility of the attributes of slice being None).

Upvotes: 2

Ron Serruya
Ron Serruya

Reputation: 4426

You can use slice

a = slice(1,3)
'hello'[a] -> ell

You can access the attributes with a.start/a.stop/a.step. The attributes are read only but you can create a new slice from them for the arithmetic requirement

Upvotes: 1

Related Questions