array Module & Memory OptimizationWhile standard Python list objects store pointers to arbitrary objects, the array module provides compact, homogeneous numerical arrays stored in contiguous C-style memory buffers.
flowchart LR
subgraph Python List (Pointer Array)
p0["Ptr [0]"] --> PyObject1["PyObject (int 10)"]
p1["Ptr [1]"] --> PyObject2["PyObject (int 20)"]
end
subgraph Python Array (Contiguous C Buffer)
buf["Contiguous Memory: [ 10 | 20 | 30 | 40 ]"]
end
'i': Signed C integer (2 or 4 bytes).'f': Floating-point number (4 bytes).'d': Double-precision float (8 bytes).import array
import sys
def demonstrate_array_efficiency() -> None:
count = 100_000
# Standard List of Ints
py_list = list(range(count))
# Contiguous C Array of Ints ('i' typecode)
c_array = array.array('i', range(count))
# Memory Size Comparison
list_size = sys.getsizeof(py_list)
array_size = sys.getsizeof(c_array)
print(f"Memory overhead for {count:,} integers:")
print(f" Standard List: {list_size / (1024*1024):.2f} MB")
print(f" Contiguous C Array: {array_size / (1024*1024):.2f} MB")
print(f" Memory Saved: {((list_size - array_size) / list_size) * 100:.1f}%")
if __name__ == "__main__":
demonstrate_array_efficiency()
array.array can only store items of the specified type code. Appending a string to an integer array raises TypeError.numpy.ndarray) instead of the standard array module.array.tofile() and array.fromfile() allow extremely fast raw binary disk reads and writes.Create a floating-point array using type code 'd' with values [1.1, 2.2, 3.3], append 4.4, and print its memory representation.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
You've completed this section! Take a quick 5-question quiz to check your understanding.