The Array-Backed List

Agenda

  1. The List Abstract Data Type (ADT)
  2. A List Data Structure
  3. Our List API
  4. Getting started: how to store our data?
  5. Built-in list as array
  6. The ArrayList data structure

1. The List Abstract Data Type (ADT)

An abstract data type (ADT) defines a conceptual model for how data may be stored and accessed.

A list ADT is a data container where:

  • values are ordered in a sequence
  • each value has at most one preceding and one succeeding value
  • a given value may appear more than once in a list

Other common ADTs (some of which we'll explore later) include:

  • Stacks
  • Queues
  • Priority Queues
  • Maps
  • Graphs

2. A List Data Structure

A list data structure is a concrete implementation of the list ADT in some programming language, which, in addition to adhering to the basic premises of the ADT, will also typically support operations that:

  • access values in the list by their position (index)
  • append and insert new values into the list
  • remove values from the list

The implementation of any data structure will generally rely on simpler, constituent data types (e.g., "primitive" types offered by the language), the choice of which may affect the runtime complexities of said operations.

3. The List API

The operations we'll be building into our list data structures will be based on the common and mutable sequence operations defined by the Python library.

In [8]:
# by default, only the result of the last expression in a cell is displayed after evaluation.
# the following forces display of *all* self-standing expressions in a cell.

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
In [ ]:
class List:        
    ### subscript-based access ###
    
    def __getitem__(self, idx):
        """Implements `x = self[idx]`"""
        pass

    def __setitem__(self, idx, value):
        """Implements `self[idx] = x`"""
        pass

    def __delitem__(self, idx):
        """Implements `del self[idx]`"""
        pass
    
    ### stringification ###
            
    def __repr__(self):
        """Supports inspection"""
        return '[]'
    
    def __str__(self):
        """Implements `str(self)`"""
        return '[]'

    ### single-element manipulation ###
    
    def append(self, value):
        pass
    
    def insert(self, idx, value):
        pass
    
    def pop(self, idx=-1):
        pass
    
    def remove(self, value):
        pass
    
    ### predicates (T/F queries) ###
    
    def __eq__(self, other):
        """Implements `self == other`"""
        return True

    def __contains__(self, value):
        """Implements `val in self`"""
        return True
    
    ### queries ###
    
    def __len__(self):
        """Implements `len(self)`"""
        return len(self.data)
    
    def min(self):
        pass
    
    def max(self):
        pass
    
    def index(self, value, i, j):
        pass
    
    def count(self, value):
        pass

    ### bulk operations ###

    def __add__(self, other):
        """Implements `self + other_array_list`"""
        return self
    
    def clear(self):
        pass
    
    def copy(self):
        pass

    def extend(self, other):
        pass

    ### iteration ###
    
    def __iter__(self):
        """Supports iteration (via `iter(self)`)"""
        pass

4. Getting started: how to store our data?

In [1]:
class List:
    def append(self, value):
        self.data=value
    
    def __getitem__(self, idx):
        """Implements `x = self[idx]`"""
        return self.data

    def __setitem__(self, idx, value):
        """Implements `self[idx] = x`"""
        self.data=value
    
    def __repr__(self):
        """Supports inspection"""
        return str(self.data)
In [11]:
l = List()
l.append(5)
l
l.append(10)
l.append(-5)
l
l[0]=12
l[0]
l[5]='HI'
l
Out[11]:
5
Out[11]:
-5
Out[11]:
12
Out[11]:
HI

5. Built-in list as array

To use the built-in list as though it were a primitive array, we will constrain ourselves to just the following APIs on a given list lst:

  1. lst[i] for getting and setting values at an existing, positive index i
  2. len(lst) to obtain the number of slots
  3. lst.append(None) to grow the list by one slot at a time
  4. del lst[len(lst)-1] to delete the last slot in a list

6. The ArrayList data structure

In [27]:
class ArrayList:
    def __init__(self):
        self.data = []
    
    def _normalize_idx(self,idx):   # attempts to change neg index to pos index
        new_idx=idx
        if new_idx<0:
            new_idx+=len(self.data)
        return new_idx
    
    def append(self, value):
        self.data.append(None)
        self.data[len(self.data)-1] = value 

    def __getitem__(self, idx):
        """Implements `x = self[idx]`"""
        assert(isinstance(idx, int))
        idx=self._normalize_idx(idx)
        if idx<0 or idx>len(self.data)-1:
            raise IndexError()
        return self.data[idx]

    def __setitem__(self, idx, value):
        """Implements `self[idx] = x`"""
        assert(isinstance(idx, int))
        idx=self._normalize_idx(idx)
        if idx<0 or idx>len(self.data)-1:
            raise IndexError()        
        self.data[idx]=value

    def __delitem__(self, idx):
        """Implements `del self[idx]`"""
        assert(isinstance(idx, int))
        idx=self._normalize_idx(idx)
        if idx<0 or idx>len(self.data)-1:
            raise IndexError()
        for i in range(idx,len(self.data)-1):
            self.data[i]=self.data[i+1] 
        del self.data[len(self.data)-1]
    
    def __len__(self):
        """Implements `len(self)`"""
        return len(self.data)
    
    def __repr__(self):
        """Supports inspection"""
        return str(self.data)
In [28]:
m=ArrayList()
m
m.append('matt')
m.append(1)
m.append((1,2,3))
m
m[2]
m[0]=5
m
Out[28]:
[]
Out[28]:
['matt', 1, (1, 2, 3)]
Out[28]:
(1, 2, 3)
Out[28]:
[5, 1, (1, 2, 3)]
In [29]:
len(m)
del m[1]
m
m['a']
Out[29]:
3
Out[29]:
[5, (1, 2, 3)]
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-29-e8a5c1f9a176> in <module>()
      2 del m[1]
      3 m
----> 4 m['a']

<ipython-input-27-3c446e7b67a0> in __getitem__(self, idx)
     15     def __getitem__(self, idx):
     16         """Implements `x = self[idx]`"""
---> 17         assert(isinstance(idx, int))
     18         idx=self._normalize_idx(idx)
     19         if idx<0 or idx>len(self.data)-1:

AssertionError: 
In [32]:
#m[5]
m
m[-1]
m[-10]
Out[32]:
[5, (1, 2, 3)]
Out[32]:
(1, 2, 3)
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-32-69868e460549> in <module>()
      2 m
      3 m[-1]
----> 4 m[-10]

<ipython-input-27-3c446e7b67a0> in __getitem__(self, idx)
     18         idx=self._normalize_idx(idx)
     19         if idx<0 or idx>len(self.data)-1:
---> 20             raise IndexError()
     21         return self.data[idx]
     22 

IndexError: