Arrays In Python — PBA Institute Tutorial
Chapter 12 · Python Programming Series
12 min read Beginner

Typed Sequences With Arrays

Although lists handle most jobs, Python also offers true arrays — fixed-type, memory-efficient sequences. The array module and the powerful numpy library expose typed arrays for situations where memory and speed matter, such as image processing, scientific computing, or game physics.

Overview

📐

Fixed Type

All elements share one type — predictable memory and speed.

🧠

Compact

Much less memory than a list of equal length.

Vectorised

NumPy operations run in C — orders of magnitude faster.

📊

Multi-D Shapes

NumPy supports 1-D, 2-D and N-D arrays for tensors and matrices.

🛠️

Toolchain Friendly

Integrates seamlessly with pandas, sklearn, TensorFlow.

Syntax

  • Import the standard module: from array import array.
  • Create with a type-code: array('i', [1, 2, 3]) for signed int.
  • For numeric power, install and use NumPy: import numpy as np.
  • Most array operations (sum, mean, sort) are vectorised — much faster than Python-level loops.
Arrays — Syntax
# Standard library
from array import array
nums = array('i', [10, 20, 30, 40])
nums.append(50)
print(nums[2])

# NumPy
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr * 2)            # [2 4 6 8]
print(arr.mean(), arr.sum())

Detailed Explanation

  • Why arrays vs lists?: Lists hold references to objects scattered in memory; arrays hold raw values contiguously. Arrays are smaller, faster to iterate, and friendly to C-level operations.
  • Type codes: 'i' int, 'f' float, 'd' double, 'b' signed byte, 'u' unicode char. Only matching types may be inserted.
  • Indexing and slicing: Identical to lists: arr[0], arr[-1], arr[1:4]. Slices return new arrays of the same type.
  • Modifying arrays: Use append, extend, insert, pop, remove — the API matches lists.
  • NumPy arrays: numpy.ndarray supports multi-dimensional shapes, broadcasting, and vectorised math. It is essential for data science, machine learning, and image processing.
  • When to use what: Use list for general purpose; array.array for compact homogeneous numeric storage; numpy for math.

Code Examples

Example 1 — Standard <code>array</code> Module
from array import array
nums = array("i", [10, 20, 30, 40])
nums.append(50)
for n in nums:
    print(n, end=" ")
Output 10 20 30 40 50
Example 2 — Type Mismatch Raises Error
from array import array
try:
    array("i", [1, 2, "three"])
except TypeError as e:
    print("TypeError:", e)
Output TypeError: an integer is required
Example 3 — NumPy Vectorised Math
import numpy as np
x = np.array([1, 2, 3, 4, 5])
print(x * 2)
print(x + 10)
print(np.sqrt(x))
Output [ 2 4 6 8 10]
[11 12 13 14 15]
[1. 1.414 1.732 2. 2.236]
Example 4 — Aggregations
import numpy as np
scores = np.array([85, 92, 78, 90, 88])
print('Sum :', scores.sum())
print('Mean:', scores.mean())
print('Max :', scores.max())
Output Sum : 433
Mean: 86.6
Max : 92
Example 5 — Boolean Masking
import numpy as np
ages = np.array([15, 22, 30, 17, 45])
adults = ages[ages >= 18]
print(adults)
Output [22 30 45]
Example 6 — Reshape NumPy Array
import numpy as np
a = np.arange(1, 13).reshape(3, 4)
print(a)
Output [[ 1 2 3 4]
 [ 5 6 7 8]
 [ 9 10 11 12]]

Real-World Use Cases

Image Processing

Images are 3-D arrays (H×W×channels) — perfect for NumPy.

Data Science

Pandas DataFrames are built on top of NumPy arrays.

Scientific Computing

Physics, astronomy, and engineering simulations live on NumPy.

Machine Learning

Models consume and produce NumPy/tensor arrays.

Audio Processing

Waveforms are 1-D arrays of samples per second.

Game Physics

Positions, velocities, and forces stored as compact arrays.

Notes & Pro Tips

  • Use the standard array only if all elements share a type and you don't need math operations.
  • For any non-trivial numerical work, use NumPy — it's the foundation of the Python data ecosystem.
  • NumPy arrays are not standard library — install with pip install numpy.
  • Always prefer vectorised NumPy operations over Python for-loops for speed.
  • Watch out for view vs copy semantics: arr[1:4] in NumPy is a view, not a copy.
  • Combine NumPy with Matplotlib for instant data visualisation.

Common Mistakes

  • Inserting wrong types: raises TypeError in the standard array.
  • Treating NumPy slices as copies: modifying a slice changes the original.
  • Using Python loops on NumPy arrays: defeats the speed benefit.
  • Mixing list and array operations: some methods differ subtly between the two.
  • Forgetting to import NumPy: np.array errors with NameError otherwise.
  • Misusing append on NumPy: np.append returns a new array, not in-place.

Practice Problems

  • Problem 1: Create a NumPy array of 20 random integers and print mean, median, and standard deviation.
  • Problem 2: Read a list of marks from the user and convert it to a NumPy array, then print the top 3 scores.
  • Problem 3: Use the standard array module to store and process 1000 daily temperature readings.
  • Problem 4: Reshape a 1-D NumPy array of 12 elements into a 3×4 matrix and print its transpose.
  • Problem 5: Given two NumPy arrays of equal length, compute element-wise sum, difference, product.
  • Problem 6: Filter all values greater than 50 from a NumPy array using boolean masking.

Interview Questions

  • Q1. What is the difference between a Python list and a Python array?
  • Q2. Why is NumPy faster than a list for numeric work?
  • Q3. Explain broadcasting in NumPy with an example.
  • Q4. What is the difference between a view and a copy in NumPy?
  • Q5. When would you use the standard array module over NumPy?
  • Q6. What is vectorisation and why is it important?

Frequently Asked Questions

  • Q1: Why use an array instead of a list?
    Arrays use less memory and are faster when elements share one type. For numeric math, NumPy arrays are dramatically faster.
  • Q2: Is NumPy part of the standard library?
    No — install it with pip install numpy. It is essentially the foundation of Python's data science stack.
  • Q3: Can I store strings in a NumPy array?
    Yes, but it allocates fixed-width strings. For text-heavy work, use lists or pandas instead.
  • Q4: What is broadcasting in NumPy?
    An automatic mechanism to align arrays of different shapes for element-wise operations — e.g. arr + 5.
  • Q5: How do I convert a list to a NumPy array?
    Use np.array(my_list). To go back, use my_array.tolist().
  • Q6: What is the difference between array.append and np.append?
    array.append mutates in place; np.append returns a new array (NumPy arrays are not resizable in place).

Summary

Arrays bring typed efficiency to Python. The standard array module is a lightweight option for homogeneous numeric data, while NumPy is the powerhouse behind virtually every scientific and data-science library in the ecosystem. Choose lists for general work, array for compact storage, and NumPy whenever performance and numerical operations matter.

Continue Learning

Previous

Go to Previous Chapter

Next

Go to Next Chapter