Python NumPy Basics Cheat Sheet

Quick reference guide for NumPy arrays. Learn array creation, reshaping, indexing, slicing, and mathematical operations.

Array Creation & Inspection

Methods to initialize numpy arrays and extract shape characteristics.

MethodSyntaxDescription
np.array()np.array(list)Creates a homogeneous multidimensional ndarray from a list.
np.arange()np.arange(start, stop, step)Creates array with evenly spaced values within a given range.
np.linspace()np.linspace(start, stop, num)Creates array with num evenly spaced values over a specified interval.
np.zeros() / np.ones()np.zeros(shape) / np.ones(shape)Initializes arrays filled with zeros or ones in the specified shape.
shape / dtypearr.shape / arr.dtypeAttributes returning dimensions and element type of the array.

Array Manipulation & Math

Routines to change array layouts and perform mathematical aggregations.

MethodSyntaxDescription
reshape()arr.reshape(new_shape)Gives a new shape to an array without changing its data.
arr.Tarr.TTranspose attribute. Reverses axes of the array.
np.concatenate()np.concatenate((a1, a2), axis=0)Joins a sequence of arrays along an existing axis.
mean() / std()arr.mean() / arr.std()Computes the arithmetic mean and standard deviation.
sum() / dot()arr.sum() / np.dot(a, b)Sums elements, or calculates the dot product matrix multiplication.

Frequently Asked Questions

Why use NumPy arrays instead of standard Python lists?

NumPy arrays are stored in contiguous memory blocks, making them significantly faster and more memory-efficient for numerical computations.

What is broadcasting in NumPy?

Broadcasting allows arithmetic operations to be performed on arrays of different shapes, expanding the smaller array to match the larger array's shape automatically.

Keep Learning

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.