Python - Python array Module and Typed Array Storage
The Python array module provides a way to store a collection of values of the same basic data type in a compact, array-like structure. Unlike a normal Python list, which can contain objects of different types, an array.array is designed for homogeneous data. This makes it useful when a program needs to store a large number of simple numeric values while using memory more efficiently than a list in many cases.
1. What Is the array Module?
The array module is part of Python's standard library, so it does not require an external installation. It provides the array() class for creating typed arrays.
The basic syntax is:
import array
numbers = array.array('i', [10, 20, 30, 40])
Here:
-
array.array()creates the array. -
'i'specifies the type of elements. -
[10, 20, 30, 40]provides the initial values.
All elements must be compatible with the specified type.
For example:
import array
numbers = array.array('i', [10, 20, 30, 40])
print(numbers)
Output:
array('i', [10, 20, 30, 40])
The 'i' type code represents a signed integer.
2. Why Use an Array Instead of a List?
Python lists are extremely flexible. A list can contain integers, strings, floating-point values, objects, and even different types together.
For example:
data = [10, 20, 30, 40]
However, Python lists store references to Python objects. When dealing with large amounts of simple numerical data, this can require considerable memory.
An array.array stores values according to a specified machine-level type. Therefore, it can provide more compact storage for certain types of numerical data.
For example:
import array
numbers = array.array('i', [10, 20, 30, 40])
The array is restricted to integer values compatible with the selected type.
This makes the array module useful when:
-
All values have the same basic type.
-
Memory usage matters.
-
Numerical values need compact storage.
-
Data needs to interact with binary or low-level data representations.
For heavy numerical and scientific computation, however, libraries such as NumPy are generally more suitable because they provide far more functionality.
3. Type Codes
The most important feature of array.array is the type code.
A type code tells Python what type of value the array should contain.
Some commonly used type codes are:
| Type Code | Data Type |
|---|---|
b |
Signed integer |
B |
Unsigned integer |
h |
Signed short integer |
H |
Unsigned short integer |
i |
Signed integer |
I |
Unsigned integer |
l |
Signed long integer |
L |
Unsigned long integer |
f |
Floating-point number |
d |
Double-precision floating-point number |
u |
Unicode character |
The exact size of some integer types can depend on the platform, so programs that require a specific binary representation should check the platform-specific characteristics rather than assuming a particular size.
Example:
import array
integers = array.array('i', [10, 20, 30])
decimals = array.array('d', [1.5, 2.5, 3.5])
print(integers)
print(decimals)
Output:
array('i', [10, 20, 30])
array('d', [1.5, 2.5, 3.5])
4. Creating an Array
An array can be created by passing a type code and an iterable of values.
import array
numbers = array.array('i', [1, 2, 3, 4, 5])
A list is not required. Other iterable objects can also be used.
For example:
import array
numbers = array.array('i', range(1, 6))
print(numbers)
Output:
array('i', [1, 2, 3, 4, 5])
An empty array can also be created:
import array
numbers = array.array('i')
Values can then be added later.
5. Accessing Array Elements
Array elements can be accessed using indexes, just like list elements.
import array
numbers = array.array('i', [10, 20, 30, 40])
print(numbers[0])
print(numbers[2])
Output:
10
30
Python also supports negative indexing.
print(numbers[-1])
Output:
40
The first element has index 0, while the last element can be accessed using index -1.
6. Modifying Array Elements
Individual elements can be changed by assigning a new compatible value.
import array
numbers = array.array('i', [10, 20, 30])
numbers[1] = 50
print(numbers)
Output:
array('i', [10, 50, 30])
The new value must be compatible with the array's declared type.
For example, an integer array cannot simply be given a string:
numbers[0] = "Python"
This produces a TypeError.
This type restriction is one of the major differences between an array and a general-purpose Python list.
7. Adding Elements
The append() method adds one element to the end of an array.
import array
numbers = array.array('i', [10, 20, 30])
numbers.append(40)
print(numbers)
Output:
array('i', [10, 20, 30, 40])
Multiple values can be added using extend().
numbers.extend([50, 60, 70])
print(numbers)
Output:
array('i', [10, 20, 30, 40, 50, 60, 70])
The values supplied to extend() must also be compatible with the array's type.
8. Inserting Elements
The insert() method allows a value to be inserted at a particular position.
import array
numbers = array.array('i', [10, 20, 40])
numbers.insert(2, 30)
print(numbers)
Output:
array('i', [10, 20, 30, 40])
The first argument specifies the position and the second argument specifies the value.
9. Removing Elements
The remove() method removes the first occurrence of a specified value.
import array
numbers = array.array('i', [10, 20, 30, 20])
numbers.remove(20)
print(numbers)
Output:
array('i', [10, 30, 20])
The pop() method removes and returns an element.
numbers = array.array('i', [10, 20, 30])
value = numbers.pop()
print(value)
print(numbers)
Output:
30
array('i', [10, 20])
An index can also be provided:
value = numbers.pop(0)
This removes the first element.
10. Traversing an Array
A for loop can be used to process every element.
import array
numbers = array.array('i', [10, 20, 30, 40])
for number in numbers:
print(number)
Output:
10
20
30
40
Arrays also support operations such as len().
print(len(numbers))
Output:
4
The index() method can be used to find the position of a value.
print(numbers.index(30))
Output:
2
11. Array Slicing
Arrays support slicing in a similar way to lists.
import array
numbers = array.array('i', [10, 20, 30, 40, 50])
part = numbers[1:4]
print(part)
Output:
array('i', [20, 30, 40])
A slice produces another array of the same type.
This is useful when only a portion of the stored data needs to be processed.
12. Checking the Array Type
The typecode attribute tells you which type code is being used.
import array
numbers = array.array('i', [10, 20, 30])
print(numbers.typecode)
Output:
i
The itemsize attribute gives the number of bytes used by each array element.
print(numbers.itemsize)
The exact value can depend on the platform and type code.
These properties can be useful when working with memory-sensitive applications or binary data.
13. Converting an Array to a List
An array can be converted into a normal Python list using tolist().
import array
numbers = array.array('i', [10, 20, 30])
values = numbers.tolist()
print(values)
Output:
[10, 20, 30]
This is useful when an API or function expects a normal Python list.
Similarly, a list can be used to create an array:
values = [10, 20, 30]
numbers = array.array('i', values)
14. Working with Bytes
One important feature of the array module is its ability to work with raw byte representations.
The tobytes() method converts the contents of an array into a bytes object.
import array
numbers = array.array('i', [10, 20, 30])
data = numbers.tobytes()
print(data)
The resulting bytes represent the array's underlying machine representation.
An array can also be reconstructed from bytes using frombytes().
import array
numbers = array.array('i')
data = array.array('i', [10, 20, 30]).tobytes()
numbers.frombytes(data)
print(numbers)
Output:
array('i', [10, 20, 30])
This capability makes the module useful in certain binary-data processing tasks.
15. Reading and Writing Arrays with Files
Arrays can also be written directly to binary files.
For example:
import array
numbers = array.array('i', [10, 20, 30, 40])
with open("numbers.bin", "wb") as file:
numbers.tofile(file)
The data can later be read back:
import array
numbers = array.array('i')
with open("numbers.bin", "rb") as file:
numbers.fromfile(file, 4)
print(numbers)
Output:
array('i', [10, 20, 30, 40])
This is particularly useful when working with simple binary data where the data type is known in advance.
16. Array Versus List
The main difference between a Python list and an array.array is their intended storage model.
| Feature | List | array.array |
|---|---|---|
| Mixed data types | Supported | Generally not |
| Same-type storage | Not required | Required |
| Memory-efficient numeric storage | Less suitable | More suitable |
| Indexing | Supported | Supported |
| Slicing | Supported | Supported |
append() |
Supported | Supported |
| Binary conversion | Not directly equivalent | Supported |
| General-purpose use | Excellent | More specialized |
For example, this is perfectly valid:
data = [10, "Python", 3.5]
But an integer array expects integer-compatible values:
import array
data = array.array('i', [10, 20, 30])
The array is therefore more restrictive but can be advantageous when the data is homogeneous.
17. Important Limitations
The array module is not a replacement for every type of collection.
First, an array can store only values compatible with its selected type code. This makes it less flexible than a list.
Second, it provides fewer high-level numerical operations than specialized numerical libraries.
For example, if a program requires matrix operations, vectorized calculations, multidimensional arrays, broadcasting, or extensive scientific functionality, NumPy is generally a better choice.
Third, the exact representation of some type codes is platform-dependent. Programs that exchange binary data between different systems should therefore carefully consider byte order and data representation.
18. Practical Example
Consider a program that stores the temperatures recorded during a week:
import array
temperatures = array.array('f', [
24.5,
25.2,
23.8,
26.1,
27.4,
25.9,
24.7
])
total = 0
for temperature in temperatures:
total += temperature
average = total / len(temperatures)
print("Average temperature:", average)
Here, 'f' indicates a floating-point array. Every temperature is stored as a floating-point value.
The program can then process the values using normal indexing, iteration, and other array operations.
Conclusion
Python's array module provides a specialized way to store homogeneous, typed data. It combines many familiar sequence operations with compact storage for basic numeric types. Important features include type codes, indexing, slicing, adding and removing elements, conversion to lists, and binary data operations through methods such as tobytes(), frombytes(), tofile(), and fromfile().
The module is particularly useful when a program needs a simple, typed sequence and wants more compact storage than a general Python list may provide. However, for general-purpose collections, lists remain more flexible, while for advanced numerical and scientific computation, specialized tools such as NumPy are usually more appropriate.