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.
| Method | Syntax | Description |
|---|---|---|
| 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 / dtype | arr.shape / arr.dtype | Attributes returning dimensions and element type of the array. |
Array Manipulation & Math
Routines to change array layouts and perform mathematical aggregations.
| Method | Syntax | Description |
|---|---|---|
| reshape() | arr.reshape(new_shape) | Gives a new shape to an array without changing its data. |
| arr.T | arr.T | Transpose 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.
Python Loops
Learn how to use Python loops to iterate over data. Master for loops, while loops, break, continue, and loop best practices with interactive examples.
How to Sort a List in Python
Learn how to sort a list in Python using the sort() method and the sorted() function. Discover custom key sorting and reverse order examples.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.