You can create a subclass listthat sets up the index to access the element:
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
(change: forgot to process the slice)
Note that there is no need to specify the ending index explicitly. It can change as your list changes in size and can be defined as mylist.offset + len(mylist)at any given time.
, , , . ( list ), , , .