array
The Python array module provides an efficient data structure for creating arrays of values (often numbers), which are stored more compactly than in standard lists.
Note: The array module isn’t limited strictly to numeric types. While most use cases are for numbers, it also supports characters with the "u" and "w" typecodes for Unicode characters.
Arrays can be particularly useful for handling large datasets where memory efficiency is a concern.
Here’s a quick example of an array containing integers:
>>> import array
>>> array.array('i', [1, 2, 3, 4])
array('i', [1, 2, 3, 4])
Key Features
Frequently Used Classes and Functions
| Object | Type | Description |
|---|---|---|
array |
Class | Creates array objects that store items of a specific type |
array.typecode |
Attribute | Returns a character code representing the type of items |
array.append() |
Method | Adds an element to the end of the array |
array.extend() |
Method | Appends items from an iterable |
array.insert() |
Method | Inserts an item in a specific position |
Examples
Create an array of integers:
>>> import array
>>> numbers = array.array('i', [1, 2, 3, 4])
>>> numbers
array('i', [1, 2, 3, 4])
Append an element to the array:
>>> numbers.append(5)
>>> numbers
array('i', [1, 2, 3, 4, 5])
Extend the array with elements from an iterable:
>>> numbers.extend([6, 7, 8])
>>> numbers
array('i', [1, 2, 3, 4, 5, 6, 7, 8])
Common Use Cases
- Handling large sequences of numbers with less memory overhead
- Performing numerical operations on values of homogeneous data types
- Interfacing with C libraries that require contiguous data
Real-World Example
Suppose you need to process a large file of integers and calculate their sum efficiently. Here’s how you can do it using the array module. Note that for this code to work, you need an integers.bin file with appropriate content:
>>> import array
>>> import os
>>> # Simulate the binary file
>>> numbers = array.array("i", [10, 20, 30, 40, 50])
>>> with open("integers.bin", "wb") as file:
... file.write(numbers.tobytes())
...
20
>>> loaded_numbers = array.array("i")
>>> with open("integers.bin", "rb") as file:
... loaded_numbers.frombytes(file.read())
...
>>> sum(loaded_numbers)
150
By using the array module, the code efficiently reads binary data and computes the sum with minimal memory usage, demonstrating the module’s utility in handling large datasets.