← Back to Python Course | Chapter 13: Data Science & Web | Lesson 1 of 14

Python NumPy Introduction

What is NumPy?

NumPy is the foundational library for numerical computing in Python, providing the ndarray type -- a fixed-type, multi-dimensional array that's dramatically faster and more memory-efficient than nested Python lists for numeric work, because its elements are stored contiguously in memory rather than as separate Python objects.

Example: What is NumPy?

python
import numpy as np
arr = np.array([1, 2, 3])
print(type(arr))

NumPy Array Attributes

Every NumPy array carries built-in metadata: .shape gives its dimensions as a tuple, .ndim gives the number of dimensions, and .size gives the total element count. Reading these attributes is how you quickly confirm an array's structure matches what a calculation expects, before running the calculation.

Example: NumPy Array Attributes

python
import numpy as np
arr = np.array([[1, 2], [3, 4]])
print(arr.shape, arr.ndim, arr.size)

Basic Mathematical Operations

NumPy applies arithmetic element-by-element across an entire array in a single vectorized operation (a + b adds every pair of corresponding elements at once), implemented in compiled C code under the hood. This is why NumPy math on large arrays runs orders of magnitude faster than an equivalent Python for loop.

Example: Basic Mathematical Operations

python
import numpy as np
a = np.array([1, 2, 3])
b = np.array([10, 20, 30])
print(a + b)

Array Data Types

Unlike a Python list, which can freely mix types, every NumPy array has one fixed dtype (like int32 or float64) shared by all its elements, chosen either automatically or explicitly via the dtype argument. Choosing a smaller dtype when precision allows can meaningfully cut an array's memory footprint.

Example: Array Data Types

python
import numpy as np
arr = np.array([1, 2, 3], dtype="float64")
print(arr.dtype)

Summary Statistics

NumPy arrays ship with built-in aggregate methods -- .sum(), .mean(), .max(), .min(), and more -- that compute across the whole array (or along a chosen axis for multi-dimensional data) far faster than manually looping and accumulating a running total in Python.

Example: Summary Statistics

python
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr.sum(), arr.mean(), arr.max())

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.