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
).