Python has no built-in array type in the sense of C or Java. For most purposes, a Python list is what people mean by an array: an ordered, indexable collection that can grow. When you need something more specialised, there are two other options: the standard library's array module, which stores numbers of one fixed type compactly, and NumPy arrays, which add fast maths on whole arrays and multiple dimensions.
readings_list = [12, 15, 11] # list: flexible, any types
from array import array
readings_array = array("i", [12, 15, 11]) # compact, integers onlyThis lesson explains how the three differ, how type codes work, which list-like operations arrays support, and how to choose. The running example stores river level readings from a monitoring station.
Representations
A list stores references to objects. Each number in a list is a full Python object with its own type information, and the list can mix types freely: [12, "offline", 14.5, None].
An array.array stores raw numeric values of a single type, packed side by side, like an array in C. That uses much less memory for large amounts of numbers, typically a quarter to an eighth of the list's size, and it guarantees every element has the same type.
A NumPy ndarray also stores packed values of one type, but adds multiple dimensions (rows and columns), and vectorised operations that apply arithmetic to every element at once in fast compiled code.
The word "array" means different things in different contexts. In tutorials for other languages it means a fixed-size typed block; in JavaScript it means something like a Python list; in data science it nearly always means a NumPy array. Check which one a piece of documentation is talking about.
Type codes
When you create an array.array, the first argument is a type code, a single character that fixes the element type:
| Code | C type | Typical size | Use for |
|---|---|---|---|
"b" / "B" | signed / unsigned char | 1 byte | small integers, bytes |
"h" | short | 2 bytes | integers up to ±32,767 |
"i" | int | 2 or 4 bytes | ordinary integers |
"q" | long long | 8 bytes | large integers |
"f" | float | 4 bytes | decimals, lower precision |
"d" | double | 8 bytes | decimals, same as Python float |
from array import array
levels = array("d", [1.82, 1.79, 1.95])
print(levels.typecode, levels.itemsize) # d 8Sizes for some codes depend on the platform and compiler, which is why itemsize exists. Values must fit the type: array("B", [300]) raises OverflowError because an unsigned byte holds 0 to 255. Use "d" for decimals unless memory is very tight, since "f" loses precision.
Sequence operations
Arrays support the operations you know from lists: indexing, slicing, len(), in, iteration, append(), extend(), insert(), pop(), remove(), index() and count(). Built-ins such as sum(), min(), max() and sorted() also work.
from array import array
readings = array("i", [12, 15, 11])
readings.append(14)
print(readings[1:3]) # array('i', [15, 11])
print(max(readings)) # 15
readings.append("high") # TypeError: 'str' object cannot be interpreted as an integerThe type is enforced on every insertion, which catches bad data early. Arrays also offer conversions that lists don't: tobytes(), frombytes(), tofile() and fromfile() read and write raw binary data efficiently, and tolist() turns the array back into a list. Arrays don't have a sort() method; use sorted(), which returns a list.
Numerical libraries
For calculations, NumPy is the standard choice. It's a separate package (pip install numpy) and its arrays support arithmetic on every element at once:
import numpy as np
levels = np.array([1.82, 1.79, 1.95])
print(levels * 100) # [182. 179. 195.]
print(levels.mean().round(2)) # 1.85With a list, * means repetition, not multiplication: [1, 2] * 3 is [1, 2, 1, 2, 1, 2]. To scale every value in a list you need a loop or comprehension, [x * 100 for x in levels], while NumPy does it in one fast operation.
A simple rule for choosing: use a list for general collections and mixed data; use array.array when you hold many numbers of one type, want low memory use, and don't need maths on the whole collection; use NumPy for numerical work, matrices and anything heading towards data analysis.
Independent practice and a worked check
Task: store compatible measurements in an array and explain when a list or NumPy array is preferable. Create a "d" array of water levels, add a reading, and print the average.
from array import array
levels = array("d", [1.82, 1.79, 1.95])
levels.append(1.88)
average = sum(levels) / len(levels)
print(f"{len(levels)} readings, average {average:.2f} m") # 4 readings, average 1.86 mA list would be better if some readings were text such as "offline"; NumPy would be better if you needed to convert every level to centimetres or calculate statistics over thousands of values. For the worked check, the values allowed in an array.array are restricted by its selected type code.
Reference and next practice
The array module documentation lists every type code and method, and the NumPy quickstart introduces ndarrays. Continue with collection methods and the NumPy lesson. Practise with the Python exercises and Python quiz.
Arrays in Python Summary
- Representations: Lists store object references while array.array stores values of one supported basic type.
- Type codes: A type code selects the basic representation of array elements.
- Sequence operations: Typed arrays support indexing, slices and compatible append operations.
- Numerical libraries: NumPy supplies multidimensional arrays and vectorized calculations as a separate package.
Arrays in Python Examples
Each example shows the code, the output it produces and what each part does.
Arrays in Python in a small program
from array import array
readings = array("i", [12, 15, 11])
readings.append(14)
print(readings.tolist())
print(sum(readings))[12, 15, 11, 14]
52Line-by-line explanation
- Lines 1 to 2An integer array (type code
"i") holding three readings. - Line 3
append()works as on a list, but only accepts integers. - Line 4
tolist()converts back to a normal list for display. - Line 5Built-ins such as
sum()work on arrays directly.
Memory use: list versus array
import sys
from array import array
count = 100_000
as_list = list(range(count))
as_array = array("i", range(count))
list_bytes = sys.getsizeof(as_list) + sum(sys.getsizeof(n) for n in as_list)
array_bytes = sys.getsizeof(as_array)
print("Same values:", as_list == as_array.tolist())
print("Array is smaller:", array_bytes < list_bytes)
print("Bytes per item in the array:", as_array.itemsize)Same values: True
Array is smaller: True
Bytes per item in the array: 4Line-by-line explanation
- Line 8A list's size includes the list itself plus every integer object it refers to.
- Line 9The array stores its 100,000 values in one packed block.
- Line 13On common platforms an
"i"item is 4 bytes, compared with roughly 28 bytes for a Pythonintobject plus an 8-byte reference.
Common Arrays in Python Mistakes
Multiplying a list to scale its values
levels = [1.82, 1.79]
print(levels * 2) # [1.82, 1.79, 1.82, 1.79]levels = [1.82, 1.79]
print([x * 2 for x in levels]) # [3.64, 3.58]For lists, * repeats the sequence. Use a comprehension, or a NumPy array, to multiply each value.
Adding the wrong type to a typed array
from array import array
readings = array("i", [12, 15])
readings.append(14.5) # TypeError: 'float' object cannot be interpreted as an integerfrom array import array
readings = array("d", [12, 15])
readings.append(14.5)Choose the type code for the data you'll store; "d" holds decimals.
Arrays in Python in Real Projects
Choosing a structure for real data
In everyday applications, lists cover almost every need: rows from a database, items in a basket, lines from a file. array.array appears in lower-level code that reads binary formats, such as audio samples or sensor dumps, where frombytes() turns raw data into numbers without a loop.
Scientific and data work uses NumPy arrays almost exclusively, and libraries such as pandas, scikit-learn and Matplotlib are built on them. A river monitoring station logging a reading every minute for a year, over half a million values, would store and analyse them as a NumPy array, which the NumPy lesson covers.
Arrays in Python FAQ
Does Python have arrays?
Python's built-in list does the job of an array in most programs. The standard library also has the array module for compact arrays of one numeric type, and the NumPy package provides multidimensional numeric arrays for scientific work.
What is the difference between a list and an array in Python?
A list can hold any mix of objects and stores a reference to each. An array.array holds only values of one numeric type, stored compactly, so it uses less memory and rejects wrong types. NumPy arrays add fast element-wise maths and multiple dimensions.
How do I create a 2D array in Python?
Use a list of lists, grid = [[0] * 3 for _ in range(2)], or a NumPy array, np.zeros((2, 3)). Avoid [[0] * 3] * 2, which repeats a reference to the same inner list, so changing one row changes both.
Is NumPy part of Python?
No. NumPy is a third-party package installed with pip install numpy. It is so widely used that many people assume it's built in, but plain Python installations don't include it.
When should I use array.array instead of a list?
When you store a large number of values of the same numeric type and memory use matters, or when you read and write raw binary data. For general programming a list is simpler, and for calculations NumPy is faster and more capable.
Arrays in Python Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
What restricts values in array.array?
Which review concern is valid for arrays in python?
Arrays in Python Quiz
2 questions to check what you learned.
What restricts values in array.array?
- Nothing
- Its selected type code
- Python ignores the distinction
Which statement correctly describes sequence operations?
- Typed arrays support indexing, slices and compatible append operations.
- Only the example output matters, not the rule
- Every operation has the same behavior