Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Python Circular List

DZone's Guide to

Python Circular List

·
Free Resource
// 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
Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}