NumPy Arrays

The NumPy array, technically called an ndarray, is a fast, memory-efficient structure for storing and processing numeric data - the fundamental building block for nearly all numerical computing in Python.

Creating Arrays

import numpy as np

arr1 = np.array([1, 2, 3, 4, 5])
print(arr1)          # [1 2 3 4 5]
print(type(arr1))    # <class 'numpy.ndarray'>

arr2 = np.array([[1, 2, 3], [4, 5, 6]])   # 2D array
print(arr2)

Common Array Creation Functions

import numpy as np

print(np.zeros(5))           # [0. 0. 0. 0. 0.]
print(np.ones((2, 3)))       # 2x3 array of ones
print(np.arange(0, 10, 2))   # [0 2 4 6 8]
print(np.linspace(0, 1, 5))  # 5 evenly spaced values between 0 and 1
print(np.random.rand(3))     # 3 random floats between 0 and 1

Why NumPy Arrays Instead of Python Lists?

Unlike a Python list, a NumPy array stores elements of a single data type in contiguous memory, allowing mathematical operations to run dramatically faster through vectorization - performing calculations on entire arrays at once instead of looping element by element.

NumPy arrays are the standard input format expected by virtually every Machine Learning library in Python, making them essential to learn well before moving into modeling.

Coming Up Next

Next, you'll learn how to perform mathematical operations directly on NumPy arrays.

Ready to Master Data Science?

Join Uncodemy's Data Science Course and build real, job-ready skills with expert mentors.

Explore Course