Python Circular List
Join the DZone community and get the full member experience.Join For Free
// 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 1 >>> cl[-1] 3 >>> cl 3 Except wraps around: >>> cl 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
Opinions expressed by DZone contributors are their own.