Implementing a circular data structure using lists

In some applications, it's advantageous to be able to define a circular data structure (a structure in which the last element is a pointer to the first). Python lists make it easy to make such a beast. A list is an ordered sequence of elements, so implementing a "ring" as a Python list is easy. "Turning" the ring consists of removing the last element from the list and placing it in the list's beginning slot. We can encapsulate this behavior in a class, which is shown below as the "Ring" class.


We'll use the Ring class in the interactive interpreter:

>>> l = [{1:1}, {2:2}, {3:3}]

(we prime a list for use in the ring)

>>> r = Ring(l)
>>> r
[{1: 1}, {2: 2}, {3: 3}]
>>> r.first()
{1: 1}
>>> r.last()
{3: 3}
>>> r.turn()

(we "turn" the ring)

>>> r
[{3: 3}, {1: 1}, {2: 2}]

(note that the element that used to be in the "last" position ({3:3}) is now in the "first" position.

>>> r.turn()
>>> r
[{2: 2}, {3: 3}, {1: 1}]

... ad infinitum ...

class Ring:
    def __init__(self, l):
        if not len(l):
            raise "ring must have at least one element"
        self._data = l

    def __repr__(self):
        return repr(self._data)

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

    def __getitem__(self, i):
        return self._data[i]

    def turn(self):
        last = self._data.pop(-1)
        self._data.insert(0, last)

    def first(self):
        return self._data[0]

    def last(self):
        return self._data[-1]

code.activestate.com ↗