Advertisement
❮ Previous: Python Dictionaries & Dictionary Comprehensions Next: Python Functions ❯

Python Arrays

In Python, understanding how data is stored in memory is crucial for performance. Unlike languages like C++ or Java, Python does not have a built-in primitive array type in its core syntax. Instead, Python provides general-purpose sequence types (list, tuple), a low-level array module, and the third-party NumPy library for high-performance numerical arrays.


1. Overview of Sequence Types vs. Arrays

Feature Python list Python tuple array Module (array.array) NumPy Array (numpy.ndarray)
Mutability Mutable (changeable) Immutable (read-only) Mutable Mutable
Data Types Heterogeneous (mixed types) Heterogeneous (mixed types) Homogeneous (single type) Homogeneous (single type)
Memory Storage Array of pointers to objects Array of pointers to objects Contiguous C-style primitive types Contiguous C-style blocks (vectorized)
Dimensions 1D (nested for 2D+) 1D (nested for 2D+) 1D only N-dimensional (ND-arrays)
Primary Use Case General-purpose collections Fixed records, dictionary keys Low-level C-interop, memory-constrained 1D data Data Science, Machine Learning, Math

Advertisement

2. Detailed Breakdown

A. General Sequence Types (list & tuple)

B. The Built-in array Module (array.array)

The built-in array module provides space-efficient arrays of uniform numeric types. Every element in an array.array must match a specific type code (e.g., 'i' for signed integers, 'f' for floats).

import array

# Create an array of 32-bit signed integers
numbers = array.array('i', [1, 2, 3, 4, 5])

print(numbers)       # Output: array('i', [1, 2, 3, 4, 5])
print(numbers.typecode) # Output: i

Try this code ❯

C. NumPy Arrays (numpy.ndarray)

For any serious numerical computing, data science, or machine learning task, Python developers bypass both lists and the array module in favor of NumPy.

NumPy arrays store data in contiguous blocks of memory, allowing for blazing-fast vectorized operations (avoiding slow Python for loops) and multi-dimensional matrices.

import numpy as np

# Create a 2D matrix
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(matrix.shape)  # Output: (2, 3)


Advertisement

3. Summary Guidelines: Which one should you use?

  1. Use list by default for standard collections of items, mixed data types, and frequent resizing.
  2. Use tuple when data should remain constant or needs to serve as a dictionary key.
  3. Use the array module only for low-level binary I/O or strict memory limits on 1D numeric data without external dependencies.
  4. Use NumPy for matrices, statistics, linear algebra, and data science workloads.
❮ Previous: Python Dictionaries & Dictionary Comprehensions Next: Python Functions ❯
Advertisement