Compact Numbers in the Standard Library: Python's array Module
This article explains how Python's array module stores numbers of one C type in a contiguous block, measures its memory saving against lists, shows its binary input and output, and describes why it is not faster for arithmetic.
A Python list does not contain its numbers: it contains pointers to separate integer or float objects, each with its own header, which is flexible but expensive when a program holds millions of values. The present article addresses the standard-library module array, whose sequences store values of a single numeric type as raw machine values in one contiguous block. Many inventory systems in games offer an appropriate image: identical items, such as arrows, stack in a single slot, whereas every unique item occupies a slot of its own. This means that an array.array keeps every element as a bare value of the same declared type, while a list keeps a separate object, and a slot for its address, for each element. The analogy, however, stops at this point, because a stack holds identical items, whereas an array holds different values that merely share one type, and it grows without any fixed limit. The article measures the memory saved, shows the binary input and output that the module supports, and identifies the costs that make it slower than a list for ordinary arithmetic. Packing numbers as tightly as a C program would, without leaving the standard library, is the secret weapon of the array module.
Creating and Using Arrays
Every array is created with a type code that fixes the C type of its elements: b, h, i, l and q for signed integers of increasing size, their upper-case forms for unsigned ones, f and d for single and double precision floats, and w for Unicode characters since Python 3.13. The sizes are minimums, not guarantees, so the attribute itemsize reports the real number of bytes on the running platform. The following example shows the list-like interface and the checks that the type code imposes.
from array import array
readings = array("i", [10, 20, 30])
readings.append(40)
readings.extend([50, 60])
print(readings) # Output: array('i', [10, 20, 30, 40, 50, 60])
print(readings[0], readings[-2:]) # Output: 10 array('i', [50, 60])
print(readings.typecode, readings.itemsize) # Output: i 4
for value in (2**31, 1.5):
try:
readings.append(value)
except (OverflowError, TypeError) as error:
print(type(error).__name__)
# Output: OverflowError
# Output: TypeError
single = array("f", [0.1])
print(single[0]) # Output: 0.10000000149011612
Appending, indexing, slicing and iteration work as in a list, but a value that does not fit in a four-byte signed integer raises OverflowError and a float in an integer array raises TypeError. The type code f converts each value to a 32-bit float, so 0.1 comes back with only about seven significant digits; d keeps the full precision of a Python float.
Measuring the Memory Saved
The saving depends on the element type, so it must be measured rather than assumed. The following example compares one million integers and one million floats stored in lists and in arrays, using tracemalloc, which counts the element objects as well as the container.
import tracemalloc
from array import array
N = 1_000_000
def traced(build):
tracemalloc.start()
data = build()
used = tracemalloc.get_traced_memory()[0]
tracemalloc.stop()
return used
int_list = traced(lambda: list(range(N)))
int_array = traced(lambda: array("i", range(N)))
float_list = traced(lambda: [float(n) for n in range(N)])
float_array = traced(lambda: array("d", (float(n) for n in range(N))))
print(int_list > 9 * int_array) # Output: True
print(float_list > 3 * float_array) # Output: True
On CPython 3.12, the list of integers occupied about 40.0 megabytes against 4.1 for the array, almost ten times more, and the list of floats about 32.4 megabytes against 8.2, about four times more. The function sys.getsizeof would have reported only 8 megabytes for the integer list, because it counts the pointers and not the objects they refer to, which is why the comparison relies on tracemalloc.
Binary Input and Output
Because an array is a block of machine values, it can be written to and read from binary streams without any conversion. The methods tobytes and frombytes, and tofile and fromfile for file objects, copy the block as it is, and byteswap reverses the byte order of every element when data comes from a machine with a different order. Arrays also implement the buffer protocol, so a memoryview can modify them in place, as examined in the article devoted to memoryview.
import io
from array import array
samples = array("h", [1, -2, 300])
print(len(samples.tobytes())) # Output: 6
stream = io.BytesIO()
samples.tofile(stream)
stream.seek(0)
loaded = array("h")
loaded.fromfile(stream, 3)
print(loaded == samples) # Output: True
swapped = array("H", [1, 256])
swapped.byteswap()
print(swapped) # Output: array('H', [256, 1])
view = memoryview(samples)
view[0] = 7
print(samples) # Output: array('h', [7, -2, 300])
Three two-byte integers produce exactly six bytes, and the stream round trip restores an equal array. These bytes use the native size and byte order of the machine that wrote them, so a portable file format should fix both explicitly, a task for which the module described in the article devoted to struct is better suited when records mix several types.
Pitfalls of the array Module
An array saves memory by storing bare values, so most of its surprises come from the conversion between those values and Python objects. Six pitfalls are distinguished, which are the following:
- Platform-dependent sizes. The code
loccupies four bytes on Windows and eight on 64-bit Linux and macOS; codes such ashandq, checked withitemsize, are the portable choice. - Overflow and precision. Values outside the range of the type raise
OverflowError, and the codefsilently rounds floats to single precision. - No vectorized arithmetic. The operator
+concatenates and*repeats, exactly as with lists; element-wise operations require a loop or NumPy. - Boxing on every read. Each access creates a new Python object from the stored value, so iterating or summing an array is slower than doing so with a list.
- Slices copy. Slicing an array creates a new array, unlike a slice of a
memoryview. - The deprecated
ucode. The type codeuhas been deprecated since Python 3.3 and its removal is announced for Python 3.16;wor an ordinarystrreplaces it.
The third, fourth and fifth pitfalls are reproduced in the following example.
import timeit
from array import array
numbers = array("i", [1, 2, 3])
print(numbers + numbers) # Output: array('i', [1, 2, 3, 1, 2, 3])
print(numbers * 2) # Output: array('i', [1, 2, 3, 1, 2, 3])
part = numbers[:2]
part[0] = 99
print(numbers[0]) # Output: 1
values = list(range(1_000_000))
packed = array("i", values)
t_list = min(timeit.repeat(lambda: sum(values), number=10, repeat=3))
t_array = min(timeit.repeat(lambda: sum(packed), number=10, repeat=3))
print(t_array > t_list) # Output: True
Neither operator adds the elements, and changing the slice leaves the original untouched. On CPython 3.12, summing one million integers took about 8.5 milliseconds for the array against 4.5 for the list, so an array is a choice for memory and binary data, not for speed.
Choosing a Container for Numbers
Consequently, the module array suits large homogeneous sequences that must be stored compactly or exchanged as raw bytes, as the following table summarizes.
| Situation | Recommended approach |
|---|---|
| Millions of numbers of one type kept in memory | array.array with an explicit type code |
| Reading or writing raw numeric data | array.array with frombytes, tofile and byteswap |
| Binary records that mix several types | The module struct |
| Element-wise arithmetic or matrices | NumPy |
| Small or mixed collections | A list |
| Sharing part of a buffer without copying | A memoryview |
| Unicode characters | str, or the code w since Python 3.13 |
Conclusion
It is concluded that an array.array stores values of one C type in a contiguous block, which reduced memory about ten times for integers and four times for floats in the measurements, and that it reads and writes raw binary data directly. This magic concerns storage, not computation: sizes depend on the platform, every read creates an object, the operators concatenate instead of adding, and slices copy. Exposing a dictionary that callers can consult but never modify is the subject of read-only mappings, which are developed in a future article of this series.