NumPy and Arrays

Use NumPy arrays for quantitative calculations.

Learning Objectives

  • Create NumPy arrays.
  • Perform vectorized arithmetic.
  • Compute basic summary statistics.
  • Understand why arrays are useful for mathematical modeling.

Motivation

Lists are useful, but quantitative work usually needs fast operations over many numbers. NumPy arrays make those operations concise and efficient.

Creating Arrays

import numpy as np

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

Vectorized Arithmetic

When you multiply an array by 2, NumPy multiplies every element.

values * 2
array([ 2,  4,  6,  8, 10])

This is different from a Python list:

[1, 2, 3] * 2
[1, 2, 3, 1, 2, 3]

Summary Statistics

values.mean(), values.min(), values.max(), values.sum()
(np.float64(3.0), np.int64(1), np.int64(5), np.int64(15))

The package includes a reusable summary helper.

from edumath.python_fundamentals import array_summary

array_summary(values)
ArraySummary(shape=(5,), mean=3.0, minimum=1.0, maximum=5.0, total=15.0)

Common Mistakes

Expecting Lists and Arrays to Behave the Same Way

[1, 2, 3] * 2 repeats a list. np.array([1, 2, 3]) * 2 doubles each value.

Ignoring Shape

Array shape tells you the dimensions of the data. Many numerical errors come from using arrays with incompatible shapes.

Practice

  1. Create an array with values [10, 20, 30].
  2. Divide every value by 10.
  3. Compute the mean.
  4. Use array_summary(...) on the array.

Solutions

Answer:

import numpy as np

values = np.array([10, 20, 30])

Answer: array([1., 2., 3.]).

values / 10

Answer: 20.0.

The mean is (10 + 20 + 30) / 3 = 20.

Answer:

from edumath.python_fundamentals import array_summary

array_summary(values)