I am a beginner of python.
I want to have arrays with arbitrary index running from p
to q
, instead of from 0.
How to create an array with q-p+1
elements with index from p
to q
?
You can create a subclass of list
which adjusts the index on item-access:
class ListWithOffset(list):
def __init__(self, offset, *a, **kw):
self.offset = offset
super().__init__(*a, **kw)
def __getitem__(self, i):
return super().__getitem__(self, self._adjust_idx(i))
def __setitem__(self, i, value):
return super().__setitem__(self, self._adjust_idx(i), value)
def __delitem__(self, i):
return super().__delitem__(self, self._adjust_idx(i))
def _adjust_idx(self, i):
if isinstance(i, slice):
return slice(i.start - self.offset if i.start is not None else None,
i.stop - self.offset if i.stop is not None else None,
i.step)
else:
return i - self.offset
(edit: forgot to handle slicing)
Note it is not necessary to specify the end-index explicitly. It can change as the size of your list changes, and can be defined as mylist.offset + len(mylist)
at any point in time.
Also note I kept the code snippet here in its simplest form, but for this to be useful you'd also need to handle the cases where the index passed is smaller than the offset. This implementation will likely return unexpected results (corresponding to list
behavior when accessing negative indices), which is probably not ideal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With