Python array Module
In this page:
What Is the array Module?
The built-in array module provides a compact, type-constrained sequence, unlike Python's regular list which can freely mix integers, strings, and objects in a single container. Every element in an array.array must share the same declared type, which lets it store data more compactly in memory.
Example: What Is the array Module?
import array
arr = array.array("i", [1, 2, 3])
print(arr)
Creating a Typed Array
You create one with array.array(typecode, values), where the typecode is a single character like i for signed int or d for double-precision float, declared up front and enforced on every insertion. Attempting to add a value of the wrong type raises a TypeError immediately, unlike a list which would silently accept it.
Example: Creating a Typed Array
import array
arr = array.array("d", [1.5, 2.5])
try:
arr.append("not a float")
except TypeError as e:
print("Error:", e)
array vs list
A plain list is more flexible and is almost always the right default choice, but an array uses noticeably less memory when storing a large number of same-typed numeric values because it avoids the overhead of storing full Python objects for each element. Reach for it in memory-constrained numeric-heavy code, not as a general replacement for list.
Example: array vs list
import array
import sys
arr = array.array("i", [1, 2, 3])
lst = [1, 2, 3]
print(sys.getsizeof(arr) < sys.getsizeof(lst))
array vs NumPy
This built-in array module is not the same as NumPy's ndarray, which is covered elsewhere on this site — NumPy is a separate third-party library offering vectorized math operations, multi-dimensional shapes, and broadcasting that the standard-library array module doesn't provide at all. array is a lightweight stdlib tool, NumPy is a full numerical computing library.
Example: array vs NumPy
import array
arr = array.array("i", [1, 2, 3])
print(type(arr))
# NumPy's ndarray adds vectorized math and multi-dimensional shapes on top of this
Common array Operations
Arrays support most list-like operations — indexing, slicing, append(), iteration — plus a few array-specific ones like tobytes() for converting to a raw byte representation, useful when interfacing with binary file formats or C-level APIs that expect packed numeric data.
Example: Common array Operations
import array
arr = array.array("i", [1, 2, 3])
arr.append(4)
print(arr[1:3])
print(arr.tobytes())
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: