Python - Arrays (array module)

Overview

Estimated time: 15–25 minutes

Python lists are general-purpose. The array module provides compact, typed arrays of basic values (e.g., bytes, ints, floats). Learn when arrays are beneficial.

Learning Objectives

  • Create and manipulate typed arrays via array('i'), array('f'), etc.
  • Understand memory/performance considerations vs lists and bytes/bytearray.
  • Know alternatives: memoryview, struct, and NumPy arrays.

Examples

from array import array

ints = array('i', [1, 2, 3])   # signed integers
ints.append(4)
print(ints)
print(ints[0])

Expected Output (repr may vary):

array('i', [1, 2, 3, 4])
1

Guidance & Patterns

  • Explain type codes ('b', 'B', 'h', 'H', 'i', 'I', 'f', 'd'). Invalid assignments raise TypeError.
  • Contrast with bytearray (mutable bytes) and when to use each.

Best Practices

  • For heavy numeric computing, prefer NumPy arrays: vectorization, BLAS-backed ops.
  • For binary protocols, combine struct with bytes/bytearray and memoryview.

Exercises

  1. Create an array of floats and compute mean and variance.
  2. Read binary data into bytearray and view as memoryview.