HomePython Page 4 - Data Structures in Python: Lists and Tuples
Lists and Tuples in the Real World - Python
Different languages use different kinds of data structures to handle the way data is arranged in memory. This article looks at two of the more common data structures used by Python.
The example application will implement a ring buffer or a bounded buffer using a list. In a bounded buffer, once the capacity is full, then the first element i.e. the oldest element is replaced with newest element. The implementation uses a class switch pattern. Here is the code:
class RingBuffer(object): """ class that implements a not-yet-full buffer """
class __Full(object): """ class that implements a full buffer """ def append(self, x): """ Append an element overwriting the oldest one. """ self.data[self.cur] = x self.cur = (self.cur+1) % self.max
def tolist(self): """ return list of elements in correct order. """ return self.data[self.cur:] + self.data[:self.cur]
def append(self, x): """ append an element at the end of the buffer. """ self.data.append(x) if len(self.data) == self.max: self.cur = 0 # Permanently change self's class from non-full to full self.__class__ = __Full
def tolist(self): """ Return a list of elements from the oldest to the newest. """ return self.data
The class defines an empty list as a buffer. The nested class __Full implements the logic to overwrite the oldest element if the buffer is full. The tolist method returns the list in the correct order. Next the append method of the outer class i.e. RingBuffer appends a new item to the end of the list. It also checks whether the length of the buffer is equal to the maximum size. If it is equal, then the buffer's state is changed to full. The tolist method returns the buffer. The following is a sample implementation that shows how to use the RingBuffer class:
That brings us to the end of this discussion. List and tuple are the basic data structures found in Python. On the basis of these, more complex structures such as trees can be developed. How to implement them will be a topic for discussion in the future. Till then…