Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Arrays in Python: Lists, `array`, and NumPy

1 min read .
Arrays in Python: Lists, `array`, and NumPy

Python has several ways to represent sequence data. The right choice depends on whether you need flexible general-purpose containers, compact typed storage, or high-performance numerical operations.

1. Lists: The Default General-Purpose Sequence

Python lists are flexible and can contain objects of different types:

numbers = [1, 2, 3, 4, 5]
mixed = [1, "Python", 3.14, True]

print(numbers[0])
numbers[1] = 10
numbers.append(6)

For most application code, a list is the correct default.

2. The Standard-Library array Module

array.array stores values of one C-compatible primitive type:

import array

int_array = array.array("i", [1, 2, 3, 4, 5])
float_array = array.array("f", [1.1, 2.2, 3.3])

The type code controls the stored representation. For example, "i" commonly represents signed integers and "f" represents C floats. Exact sizes are platform-dependent, so check the array documentation when binary compatibility matters.

Standard sequence operations still work:

int_array[1] = 10
subset = int_array[1:4]
int_array.append(6)

array.array can be useful for compact primitive data, binary I/O, and interoperability where a Python list would add unnecessary object overhead.

3. NumPy Arrays for Numerical Computing

For vectorized mathematics and multidimensional numerical data, NumPy is the standard ecosystem choice:

python -m pip install numpy
import numpy as np

values = np.array([1, 2, 3, 4, 5])
print(values * 2)

Output:

[ 2  4  6  8 10]

NumPy performs many operations in optimized compiled code instead of requiring explicit Python loops.

Multidimensional arrays are also natural:

matrix = np.array([
    [1, 2, 3],
    [4, 5, 6],
])

print(matrix.shape)
print(matrix[:, 1])

4. Which One Should You Use?

Use a list when:

  • You need a normal application collection.
  • Elements may be arbitrary Python objects.
  • You frequently append, remove, or reorganize items.

Use array.array when:

  • Values are homogeneous primitive numbers.
  • Compact storage or binary interoperability is useful.
  • You do not need NumPy’s broader numerical features.

Use NumPy when:

  • You perform numerical or scientific computation.
  • You need multidimensional arrays.
  • Vectorized operations, broadcasting, or numerical libraries matter.

Conclusion

Python’s ordinary list is the best default sequence for general code. array.array provides compact typed primitive storage, while NumPy is designed for high-performance numerical work. Choose based on the operations and data model you actually need rather than treating all three as interchangeable.

Related Posts

chevron-up