Sobes.tech
Middle+

How would you implement a data structure similar to a list in Python if it did not exist?

sobes.tech AI

Answer from AI

I would implement it based on a dynamic array.

Main principles:

  1. Using a fixed-size array to store elements.
  2. When reaching the capacity limit of the array, create a new larger array (usually 1.5 - 2 times larger) and copy all elements into it.
  3. Store the current number of elements.
  4. Provide methods for adding, removing, accessing by index, iterating, and determining length.

Example of a basic structure:

class MyList:
    def __init__(self, capacity=10):
        self._capacity = capacity # Maximum capacity
        self._size = 0           # Current number of elements
        self._array = [None] * self._capacity # Internal array

    def _resize(self, new_capacity):
        new_array = [None] * new_capacity
        for i in range(self._size):
            new_array[i] = self._array[i]
        self._array = new_array
        self._capacity = new_capacity

    def append(self, item):
        if self._size == self._capacity:
            self._resize(self._capacity * 2) # Double the size
        self._array[self._size] = item
        self._size += 1

    def __len__(self):
        return self._size

    def __getitem__(self, index):
        if 0 <= index < self._size:
            return self._array[index]
        raise IndexError("index out of range")

    def __setitem__(self, index, item):
        if 0 <= index < self._size:
            self._array[index] = item
        else:
            raise IndexError("index out of range")

    def __iter__(self):
        for i in range(self._size):
            yield self._array[i]

    # Additional methods: insert, pop, remove, index, slices, etc.

Advantages of this approach:

  • Index access (get/set) in O(1) on average.
  • Fast appending at the end (append) in O(1) on average (due to amortized reallocation).
  • Iteration in O(n), where n is the number of elements.

Complexities and trade-offs:

  • Inserting or deleting from the middle requires shifting elements, which takes O(n) time.
  • Reallocation and copying can be costly operations but occur rarely and are spread over many add operations (amortized analysis).

To fully mimic list, many other methods (insert, pop, remove, index, slices, etc.) should be implemented while maintaining the efficiency of standard operations.