Introduction
The array module provides space-efficient storage for homogeneous primitive types. It's more memory-efficient than lists for numeric data.
Basic Array
from array import array
# Create array of integers
numbers = array("i", [1, 2, 3, 4, 5])
print(numbers) # array('i', [1, 2, 3, 4, 5])
print(numbers[0]) # 1
print(numbers[2:4]) # array('i', [3, 4])
# Array types: 'b' (signed char), 'B' (unsigned char),
# 'h' (short), 'H' (unsigned short), 'i' (int), 'I' (unsigned int),
# 'f' (float), 'd' (double)
Array Methods
from array import array
arr = array("i", [3, 1, 4, 1, 5])
arr.append(9)
arr.extend([2, 6])
arr.insert(0, 0)
arr.remove(1) # Remove first occurrence
arr.pop()
arr.reverse()
print(list(arr))
Array from Bytes
from array import array
# Create from bytes
data = b"\x01\x02\x03\x04"
arr = array("B", data)
print(list(arr)) # [1, 2, 3, 4]
# Convert to bytes
back_to_bytes = arr.tobytes()
print(back_to_bytes) # b'\x01\x02\x03\x04'
Type Codes
from array import array
# Numeric types
ints = array("i", [1, 2, 3])
floats = array("d", [1.1, 2.2, 3.3])
# Characters
chars = array("u", "Hello") # Unicode
bytes_arr = array("b", b"Hello") # Signed bytes
# Type info
print(array.typecodes) # All available type codes
File I/O with Array
from array import array
import io
# Write to file
with open("data.bin", "wb") as f:
arr = array("i", [1, 2, 3, 4, 5])
arr.tofile(f)
# Read from file
with open("data.bin", "rb") as f:
arr = array("i")
arr.fromfile(f, 5)
print(arr)
Practice Problems
- Create array with different type codes
- Use array methods (append, extend, remove)
- Convert between bytes and array
- Read/write array to file
- Compare array with list for memory