DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Chris has posted 1 posts at DZone. View Full User Profile

Python Circular List

02.25.2010
| 6468 views |
  • submit to reddit
        // 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]
    1
    
    >>> cl[-1]
    3
    
    >>> cl[2]
    3
    
    Except wraps around:
    >>> cl[3]
    1
    
    >>> cl[-4]
    3
    
    Slices work
    >>> cl[0:2]
    [1, 2]
    
    but only in range.
    """
    def __getitem__(self, key):
        
        # try normal list behavior
        try:
            return super(CircularList, self).__getitem__(key)
        except IndexError:
            pass
        # key can be either integer or slice object,
        # only implementing int now.
        try:
            index = int(key)
            index = index % self.__len__()
            return super(CircularList, self).__getitem__(index)
        except ValueError:
            raise TypeError