Python Arrays
Array Module Basics
Python's array module provides compact, homogeneous arrays of basic numeric types. Unlike lists, all elements share a single C type (specified by a type code), which makes arrays more memory efficient and well-suited for binary I/O.
Common type codes include: 'b' (signed char), 'B' (unsigned char), 'h' (signed short), 'H' (unsigned short), 'i' (signed int), 'I' (unsigned int), 'l' (signed long), 'L' (unsigned long), 'f' (float, 4 bytes), and 'd' (double, 8 bytes).
# Importing and creating arrays
import array
# Creating arrays with different type codes
# 'i' for signed integers, 'f' for 32-bit floats, 'd' for 64-bit floats
int_array = array.array('i', [1, 2, 3, 4, 5])
float_array = array.array('f', [1.5, 2.5, 3.5])
print(f"Integer array: {int_array}")
print(f"Float array: {float_array}")
print(f"Type code of int_array: {int_array.typecode}")
print(f"Itemsize of int_array: {int_array.itemsize} bytes")
Integer array: array('i', [1, 2, 3, 4, 5]) Float array: array('f', [1.5, 2.5, 3.5]) Type code of int_array: i Itemsize of int_array: 4 bytes
Array Operations
Arrays support familiar sequence operations (indexing, slicing, len, append, insert, remove). Remember that values must match the array's type; assigning an incompatible value raises TypeError or OverflowError.
# Array operations
import array
numbers = array.array('i', [10, 20, 30, 40, 50])
# Accessing elements
print(f"First element: {numbers[0]}")
print(f"Last element: {numbers[-1]}")
# Slicing (returns an array of the same type)
print(f"First three: {numbers[:3]}")
# Modifying elements
numbers[1] = 25
print(f"After modification: {numbers}")
# Appending
numbers.append(60)
print(f"After append: {numbers}")
# Length
print(f"Length: {len(numbers)}")
First element: 10 Last element: 50 First three: array('i', [10, 20, 30]) After modification: array('i', [10, 25, 30, 40, 50]) After append: array('i', [10, 25, 30, 40, 50, 60]) Length: 6
Array Methods
The array module includes methods similar to lists and some that are handy for binary I/O. Below are common ones you’ll use day to day.
# Array methods
import array
arr = array.array('i', [5, 2, 8, 1, 9, 2])
# Count occurrences
print(f"Count of 2: {arr.count(2)}")
# Extend array from iterable
arr.extend([10, 11, 12])
print(f"After extend: {arr}")
# Find index (first occurrence)
print(f"Index of 8: {arr.index(8)}")
# Insert element at position
arr.insert(2, 99)
print(f"After insert: {arr}")
# Remove first matching value
arr.remove(2)
print(f"After remove: {arr}")
# Reverse in place
arr.reverse()
print(f"Reversed: {arr}")
Count of 2: 2 After extend: array('i', [5, 2, 8, 1, 9, 2, 10, 11, 12]) Index of 8: 2 After insert: array('i', [5, 2, 99, 8, 1, 9, 2, 10, 11, 12]) After remove: array('i', [5, 99, 8, 1, 9, 2, 10, 11, 12]) Reversed: array('i', [12, 11, 10, 2, 9, 1, 8, 99, 5])
Arrays vs Lists
Arrays are more memory efficient than lists for large collections of numeric data because they store raw C values of a single type. However, for general Python-level looping and per-element operations, arrays are not necessarily faster than lists.
Use arrays when you need compact numeric storage or binary I/O. For high-performance numeric computing (vectorization, linear algebra), prefer third-party libraries like NumPy.
# Arrays vs Lists
import array
import sys
# Memory comparison (values vary by platform/interpreter)
list_data = [1, 2, 3, 4, 5]
array_data = array.array('i', [1, 2, 3, 4, 5])
print("List memory:", sys.getsizeof(list_data), "bytes")
print("Array memory:", sys.getsizeof(array_data), "bytes")
# Converting between lists and arrays
list_from_array = array_data.tolist()
array_from_list = array.array('i', list_data)
print("List from array:", list_from_array)
print("Array from list:", array_from_list)
List memory: <platform-dependent> bytes Array memory: <platform-dependent> bytes List from array: [1, 2, 3, 4, 5] Array from list: array('i', [1, 2, 3, 4, 5])