Python Arrays
Python Arrays: Lists, array.array, and NumPy Compared
Python does not have a single built-in keyword called array like Java or C. Instead, Python gives you three array-like tools depending on your job: list for general data, array.array for compact typed sequences, and NumPy ndarray for fast math.
For 90% of everyday scripting, a standard Python list is the right choice because it integrates everywhere with zero imports.
Comparing Python's Three Array Options
| Option | Mixed Types? | Memory Footprint | Best Use Case |
|---|---|---|---|
list |
Yes | Higher (object pointers) | General collections, API data |
array.array |
No (single C type) | Compact | Binary streams, dense numeric lists |
numpy.ndarray |
No (fixed dtype) | Very compact | Matrix math, ML, data science |
Using the Standard Library array Module
When you store millions of uniform integers or floats without installing third-party libraries, array.array packs raw C values tightly in memory. It supports indexing, slicing, .append(), and .extend() just like a list, while enforcing a strict single-byte type code across every element.
from array import array
# 'i' = signed integer, 'd' = double-precision float
sensor_ids = array("i", [101, 102, 103])
sensor_ids.append(104)
temperatures = array("d", [21.5, 22.1, 20.8])
print(sensor_ids[1], sum(temperatures) / len(temperatures))
Common Mistakes to Avoid
- Inserting the wrong type into
array.array: Appending"105"or3.5to an integerarray("i")raisesTypeError. - Looping over huge numeric lists in pure Python: For heavy math on thousands of numbers, switch to
numpyvectorized operations instead of Pythonforloops. - Mutating slices inconsistently:
listslicing returns a newlist, whereas slicing a NumPy array returns a view sharing the same memory.
Frequently Asked Questions
Are Python lists technically dynamic arrays?
Yes. Under the hood, CPython stores a list as a contiguous C array of pointers to Python objects, resizing automatically as you append items.
Do I need to install anything for array.array?
No. The array module is built directly into the Python standard library.
How do I inspect type codes for array.array?
Common codes include 'i' (signed int), 'I' (unsigned int), 'f' (32-bit float), and 'd' (64-bit float).
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.