Over a million developers have joined DZone.

Python Circular List

// description of your code here
Simple, perhaps incomplete implementation of a Circular List in Python. Subclasses list and overrides __getitem__. The only special behavior is that attempts to access indices which are out of bounds will wrap around - accessing mylist(len(mylist)) should return the first item in the list instead of an IndexError

Slice operations must still be 'in bounds'

First tries list's __getitem__. If that is not successful, it converts the index key to an integer, then calculates the appropriate 'in bounds' index and returns whatever is stored there.

If converting the key to integer fails, TypeError is raised.

class CircularList(list):
    A list that wraps around instead of throwing an index error.
    Works like a regular list:
    >>> cl = CircularList([1,2,3])
    >>> cl
    [1, 2, 3]
    >>> cl[0]
    >>> cl[-1]
    >>> cl[2]
    Except wraps around:
    >>> cl[3]
    >>> cl[-4]
    Slices work
    >>> cl[0:2]
    [1, 2]
    but only in range.
    def __getitem__(self, key):
        # try normal list behavior
            return super(CircularList, self).__getitem__(key)
        except IndexError:
        # key can be either integer or slice object,
        # only implementing int now.
            index = int(key)
            index = index % self.__len__()
            return super(CircularList, self).__getitem__(index)
        except ValueError:
            raise TypeError

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}