Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array in python with arbitrary index

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?

like image 664
velut luna Avatar asked Jul 13 '14 05:07

velut luna


Video Answer


1 Answers

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.

like image 70
shx2 Avatar answered Oct 06 '22 00:10

shx2