• Python's indexing conventions

    From Stefan Ram@21:1/5 to Stefan Ram on Tue Dec 31 21:00:26 2024
    ram@zedat.fu-berlin.de (Stefan Ram) wrote or quoted:
    |Raymond Boute <raymond.boute@pandora.be> wrote or quoted:
    Moreover, using index -1 for the last item is a bad choice
    |This feature is the bee's knees, man.

    I was just looking for a list with a sort of "max-out" vibe
    that turns all negative indices into zeros. My AI wingman
    whipped it up for me.

    In my code, it goes by "SourceList":

    s = list( 'Example' )
    t = SourceList( 'Example' )

    print( repr( s[ -1: 2 ] ))
    print( repr( t[ -1: 2 ] ))

    spits out:

    []
    ['E', 'x']

    'cause "t[ -1: 2 ]" is basically the same as "s[ 0: 2 ]".

    Here's the whole shebang:

    from collections.abc import MutableSequence

    class SourceList(MutableSequence):
    '''
    Interpret all negative indices in subscriptions and slices to mean 0.
    '''
    def __init__(self, iterable=None):
    self._list = list(iterable) if iterable is not None else []

    def _normalize_index(self, index):
    return max(0, index) if isinstance(index, int) else index

    def _normalize_slice(self, key):
    start = self._normalize_index(key.start) if key.start is not None else None
    stop = self._normalize_index(key.stop) if key.stop is not None else None
    return slice(start, stop, key.step)

    def __getitem__(self, key):
    if isinstance(key, slice):
    key = self._normalize_slice(key)
    else:
    key = self._normalize_index(key)
    return self._list[key]

    def __setitem__(self, key, value):
    if isinstance(key, slice):
    key = self._normalize_slice(key)
    else:
    key = self._normalize_index(key)
    self._list[key] = value

    def __delitem__(self, key):
    if isinstance(key, slice):
    key = self._normalize_slice(key)
    else:
    key = self._normalize_index(key)
    del self._list[key]

    def __len__(self):
    return len(self._list)

    def insert(self, index, value):
    self._list.insert(self._normalize_index(index), value)

    def __str__(self):
    return f"SourceList({self._list})"

    def __repr__(self):
    return self.__str__()

    s = list( 'Example' )
    t = SourceList( 'Example' )

    print( repr( s[ 0: 2 ] ))
    print( repr( t[ -1: 2 ] ))

    .

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)