Implementation of Dynamic Array in Python

In Python, dynamic arrays automatically resize when elements are added or removed. Python's built-in list is actually a dynamic array that can grow and shrink during runtime, unlike static arrays with fixed sizes.

Understanding Mutable vs Immutable Objects

Python objects fall into two categories ?

  • Mutable: Lists, sets, and dictionaries can be modified after creation
  • Immutable: Numbers, strings, and tuples cannot be changed after creation

Python Lists as Dynamic Arrays

Let's see how Python lists work as dynamic arrays ?

# Create an empty list
numbers = []
print(f"Type: {type(numbers)}")
print(f"Initial length: {len(numbers)}")

# Add items dynamically
numbers = [2, 4, 6]
print(f"After adding elements: {numbers}")

# Append more items
numbers.append('TutorialsPoint')
print(f"After append: {numbers}")
Type: <class 'list'>
Initial length: 0
After adding elements: [2, 4, 6]
After append: [2, 4, 6, 'TutorialsPoint']

Removing Elements

# Remove the last item
numbers = [2, 4, 6, 'TutorialsPoint']
removed_item = numbers.pop()
print(f"Removed: {removed_item}")
print(f"List after removal: {numbers}")
Removed: TutorialsPoint
List after removal: [2, 4, 6]

How Dynamic Arrays Work Internally

When a dynamic array reaches capacity, it follows these steps ?

  1. Allocate a new array with larger capacity (typically double)
  2. Copy all existing elements to the new array
  3. Update the reference to point to the new array
  4. Insert the new element

Custom Dynamic Array Implementation

Here's how to implement a dynamic array from scratch using Python's ctypes module ?

import ctypes

class DynamicArray:
    def __init__(self):
        self.n = 0  # Number of elements
        self.capacity = 1  # Initial capacity
        self.A = self.make_array(self.capacity)
    
    def __len__(self):
        return self.n
    
    def __getitem__(self, k):
        if not 0 <= k < self.n:
            raise IndexError('Index out of bounds')
        return self.A[k]
    
    def append(self, element):
        if self.n == self.capacity:
            self._resize(2 * self.capacity)
        
        self.A[self.n] = element
        self.n += 1
    
    def _resize(self, new_capacity):
        B = self.make_array(new_capacity)
        for k in range(self.n):
            B[k] = self.A[k]
        
        self.A = B
        self.capacity = new_capacity
    
    def make_array(self, new_capacity):
        return (new_capacity * ctypes.py_object)()

# Test the dynamic array
arr = DynamicArray()
print(f"Initial length: {len(arr)}")

arr.append(1)
print(f"After adding 1: length = {len(arr)}")

arr.append('TutorialsPoint')
print(f"After adding string: length = {len(arr)}")
print(f"Element at index 1: {arr[1]}")
Initial length: 0
After adding 1: length = 1
After adding string: length = 2
Element at index 1: TutorialsPoint

Key Features

Feature Static Array Dynamic Array
Size Fixed at creation Grows/shrinks automatically
Memory Allocated once Reallocated when needed
Performance O(1) access O(1) average, O(n) resize

Conclusion

Dynamic arrays automatically manage memory allocation, making them flexible for varying data sizes. Python's built-in lists implement this concept efficiently, but understanding the underlying mechanism helps in choosing appropriate data structures for specific use cases.

Updated on: 2026-03-25T05:16:57+05:30

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements