Python NumPy Tutorial for Beginners
This Python NumPy tutorial explains how to install NumPy, create one-dimensional and multidimensional arrays, select suitable data types, reshape arrays, perform element-wise operations, filter values, calculate statistics, and work with commonly used NumPy functions.
The examples assume that you already know basic Python concepts such as variables, lists, functions, loops, and importing modules. You can run the examples in a Python terminal, a script, or a Jupyter Notebook.
What Is NumPy in Python?
NumPy, short for Numerical Python, is a Python library for working with numerical data. Its central object is the ndarray, an array that can have one or more dimensions. NumPy also provides functions for array creation, element-wise calculations, aggregation, random sampling, linear algebra, and other numerical operations.
A NumPy array generally stores elements of one data type. This differs from a regular Python list, which can contain values of different types in the same list.
Why Use NumPy Instead of Python Lists?
NumPy is commonly used when a program needs to process many numerical values or represent data in rows, columns, and higher-dimensional structures.
- NumPy supports element-wise calculations without writing an explicit Python loop for each value.
- Its arrays use a consistent data type and a compact memory representation.
- It provides integer, unsigned integer, floating-point, complex, Boolean, string, and other data types with selectable precision.
- Its array operations are used by libraries for data analysis, scientific computing, image processing, and machine learning.

Install NumPy with pip
For a basic NumPy installation, open a terminal or command prompt and run python -m pip install numpy. Using python -m pip helps ensure that pip installs the package for the Python interpreter represented by the python command.
python -m pip install numpy
The older command below installs NumPy together with several additional scientific and notebook packages. Use it only when you need the complete set.
python -m pip install --user numpy scipy matplotlib ipython jupyter pandas sympy nose
The following archived command-prompt output shows how pip downloaded the requested packages and their dependencies at the time the example was recorded. Package versions and download messages will differ on a current system.
C:\>python -m pip install --user numpy scipy matplotlib ipython jupyter pandas sympy nose
Collecting numpy
Downloading https://files.pythonhosted.org/packages/94/b5/f4bdf7bce5f8b35a2a83a0b70c545ca061a50b54724b5287505064906b14/numpy-1.16.0-cp37-cp37m-win32.whl (10.0MB)
100% |????????????????????????????????| 10.0MB 765kB/s
Collecting scipy
Downloading https://files.pythonhosted.org/packages/88/f2/7f16c94e22c9714b0dc417bdaa7d6eb9ec9f90fd5d5c6221769f73b3f5dd/scipy-1.2.0-cp37-cp37m-win32.whl (26.8MB)
100% |????????????????????????????????| 26.8MB 471kB/s
Collecting matplotlib
Downloading https://files.pythonhosted.org/packages/3f/16/4500e22ea8d11f4946bd902695d0113f82a0aaca45f352478f157ca6623d/matplotlib-3.0.2-cp37-cp37m-win32.whl (8.7MB)
100% |????????????????????????????????| 8.7MB 3.4MB/s
Collecting ipython
Downloading https://files.pythonhosted.org/packages/f0/b4/a9ea018c73a84ee6280b2e94a1a6af8d63e45903eac2da0640fa63bca4db/ipython-7.2.0-py3-none-any.whl (765kB)
100% |????????????????????????????????| 768kB 1.3MB/s
Collecting jupyter
After a successful installation, pip prints a list of installed packages. The exact list depends on your operating system, Python version, existing environment, and the packages requested.
Successfully installed MarkupSafe-1.1.0 Send2Trash-1.5.0 backcall-0.1.0 bleach-3.1.0 colorama-0.4.1 cycler-0.10.0 decorator-4.3.2 defusedxml-0.5.0 entrypoints-0.3 ipykernel-5.1.0 ipython-7.2.0 ipython-genutils-0.2.0 ipywidgets-7.4.2 jedi-0.13.2 jinja2-2.10 jsonschema-2.6.0 jupyter-1.0.0 jupyter-client-5.2.4 jupyter-console-6.0.0 jupyter-core-4.4.0 kiwisolver-1.0.1 matplotlib-3.0.2 mistune-0.8.4 mpmath-1.1.0 nbconvert-5.4.0 nbformat-4.4.0 nose-1.3.7 notebook-5.7.4 numpy-1.16.0 pandas-0.24.0 pandocfilters-1.4.2 parso-0.3.2 pickleshare-0.7.5 prometheus-client-0.5.0 prompt-toolkit-2.0.8 pygments-2.3.1 pyparsing-2.3.1 python-dateutil-2.7.5 pytz-2018.9 pywinpty-0.5.5 pyzmq-17.1.2 qtconsole-4.4.3 scipy-1.2.0 six-1.12.0 sympy-1.3 terminado-0.8.1 testpath-0.4.2 tornado-5.1.1 traitlets-4.3.2 wcwidth-0.1.7 webencodings-0.5.1 widgetsnbextension-3.4.2
Verify the NumPy Installation
Import NumPy and print its version to confirm that the package is available to the current Python interpreter.
import numpy
print(numpy.__version__)
If the import succeeds, Python prints the installed NumPy version. If you receive ModuleNotFoundError, check that NumPy was installed in the same environment in which the program is running.
Archived command-prompt example
C:\>python
Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 14:05:16) [MSC v.1915 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
>>> print(numpy.__version__)
1.16.0
>>>
The version shown above belongs to the archived example. Your installed version will usually be different.
Update an Existing NumPy Installation
You can update NumPy with pip using the following command.
pip install numpy --upgrade
An equivalent interpreter-specific command is shown below.
python -m pip install --upgrade numpy
NumPy Data Types and Precision
The dtype of a NumPy array determines how its values are represented. Selecting an appropriate type can reduce memory use, but the type must still be large and precise enough for the data and calculations.
| Data type | Description |
|---|---|
| bool_ | Boolean value stored as True or False |
| int_ | Default signed integer type; exact size depends on the platform |
| intc | Integer compatible with a C int |
| intp | Integer type used for indexing array elements |
| int8 | Signed 8-bit integer from -128 to 127 |
| int16 | Signed 16-bit integer from -32768 to 32767 |
| int32 | Signed 32-bit integer |
| int64 | Signed 64-bit integer |
| uint8 | Unsigned 8-bit integer from 0 to 255 |
| uint16 | Unsigned 16-bit integer from 0 to 65535 |
| uint32 | Unsigned 32-bit integer |
| uint64 | Unsigned 64-bit integer |
| float16 | Half-precision floating-point value |
| float32 | Single-precision floating-point value |
| float64 | Double-precision floating-point value |
| complex64 | Complex number represented by two 32-bit floating-point components |
| complex128 | Complex number represented by two 64-bit floating-point components |
You can inspect an array’s type using its dtype attribute and convert it with astype(). A conversion may lose information when the target type has a smaller range or lower precision.
import numpy as np
values = np.array([10.5, 20.25, 30.75])
print(values.dtype)
integers = values.astype(np.int32)
print(integers)
print(integers.dtype)
float64
[10 20 30]
int32
Import NumPy with the np Alias
NumPy must be imported before its functions and types can be used. You can import it with its full package name.
import numpy
Most NumPy examples use np as the alias. The alias is not required, but it makes calls such as np.array() and np.mean() shorter.
import numpy as np
The remaining examples use np to refer to the NumPy package.
Create a One-Dimensional NumPy Array
NumPy provides several array-creation functions. The correct function depends on whether you already have the values, need a numerical range, or need a fixed number of evenly spaced points.
- array()
>>> import numpy as np
>>> a = np.array([5, 8, 12])
>>> a
array([ 5, 8, 12])np.array()converts an array-like object, such as a Python list or tuple, into a NumPy array. - arange()
The function name is arange, meaning array range.numpy.arange()accepts a start value, an excluded stop value, and a step.>>> import numpy as np
>>> a = np.arange(1, 15, 2)
>>> a
array([ 1, 3, 5, 7, 9, 11, 13])Here,
1is included,15is excluded, and adjacent values differ by2. - linspace()
numpy.linspace()creates a requested number of evenly spaced values between two endpoints.>>> import numpy as np
>>> a = np.linspace(1, 15, 7)
>>> a
array([ 1. , 3.33333333, 5.66666667, 8. , 10.33333333, 12.66666667, 15. ])Here,
1and15are the endpoints, and7is the number of generated values.
Use arange() when the step size is the main requirement. Use linspace() when the number of samples and inclusion of both endpoints are the main requirements.
Create and Reshape a Two-Dimensional NumPy Array
A two-dimensional array stores values along two axes, commonly interpreted as rows and columns. You can create one directly from nested lists or reshape an existing one-dimensional array.
The reshape() method accepts the target dimensions. The total number of elements must remain unchanged. For example, an array containing six elements can be reshaped to (3, 2), (2, 3), or (1, 6).
>>> import numpy as np
>>> a = np.array([8, 2, 3, 7, 9, 1])
>>> a
array([8, 2, 3, 7, 9, 1])
>>> a = a.reshape(3, 2)
>>> a
array([[8, 2],
[3, 7],
[9, 1]])
>>>
If the requested dimensions do not account for every element, NumPy raises a ValueError.
>>> a.reshape(2, 4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: cannot reshape array of size 6 into shape (2,4)
The same six values can be rearranged into other compatible shapes.
>>> a = a.reshape(3, 2)
>>> a
array([[8, 2],
[3, 7],
[9, 1]])
>>> a = a.reshape(2, 3)
>>> a
array([[8, 2, 3],
[7, 9, 1]])
>>> a = a.reshape(1, 6)
>>> a
array([[8, 2, 3, 7, 9, 1]])
>>>
You can also let NumPy infer one dimension by passing -1.
import numpy as np
values = np.arange(12)
matrix = values.reshape(3, -1)
print(matrix)
print(matrix.shape)
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
(3, 4)
Create a NumPy Array Filled with Zeros
Use np.zeros() to create an array of a specified shape with every element initialized to zero. The default data type is usually float64.
>>> import numpy as np
>>> a = np.zeros((4, 5))
>>> a
array([[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]])
>>>
Inspect the array’s data type through its dtype attribute.
>>> a.dtype
dtype('float64')
Pass a NumPy data type through the dtype argument when a different representation is required.
>>> a = np.zeros((4, 5), np.int16)
>>> a
array([[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]], dtype=int16)
In this example, np.int16 creates an array of signed 16-bit integers.
Create a NumPy Array Filled with Ones
Use np.ones() to create an array whose elements are initialized to one.
>>> import numpy as np
>>> a = np.ones((3,7))
>>> a
array([[1., 1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1., 1.]])
>>> a.dtype
dtype('float64')
>>>
As with zeros(), you can specify the required type through dtype.
>>> a = np.ones((3,7), dtype=np.uint8)
>>> a
array([[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1]], dtype=uint8)
>>> a.dtype
dtype('uint8')
>>>
The array above uses uint8, an unsigned 8-bit integer type.
Create NumPy Arrays with Random Values
NumPy’s random module can generate arrays for simulations, testing, sampling, and example data. The following archived example uses np.random.random() to create values from the interval beginning at 0 and ending before 1.
>>> a = np.random.random((3,2))
>>> a
array([[0.08832623, 0.80635251],
[0.28991211, 0.9976203 ],
[0.5372018 , 0.53011979]])
>>> a.dtype
dtype('float64')
>>>
The first random refers to NumPy’s random module, while the second is the function name. The randint() function can generate random integers from a specified interval.
>>> a = np.random.randint(0,8,12)
>>> a
array([5, 3, 4, 5, 1, 7, 3, 6, 5, 5, 2, 6])
>>>
For new code, a generator created by np.random.default_rng() keeps the random-number source explicit. Supplying a seed makes the example reproducible.
import numpy as np
rng = np.random.default_rng(seed=42)
values = rng.integers(0, 10, size=(2, 4))
print(values)
[[0 7 6 4]
[4 8 0 6]]
Inspect NumPy Array Size, Shape, Dimensions, and Type
Several array attributes describe its structure:
sizegives the total number of elements.shapegives the length of each axis.ndimgives the number of axes.dtypegives the element data type.itemsizegives the number of bytes used by one element.
Find the Total Number of NumPy Array Elements
The size attribute returns the total number of elements, regardless of how those elements are arranged.
>>> a
array([[8, 2],
[3, 7],
[9, 1]])
>>> a.size
6
>>>
The returned value is a Python integer.
Read the Shape of a NumPy Array
The shape attribute returns a tuple. A shape of (4, 5) describes four rows and five columns.
>>> a = np.zeros((4, 5), np.int16)
>>> a
array([[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]], dtype=int16)
>>> a.shape
(4, 5)
>>>
The same attribute works for arrays with more than two dimensions.
>>> a = np.zeros((4, 5, 2, 2), np.int16)
>>> a
array([[[[0, 0],
[0, 0]],
[[0, 0],
[0, 0]],
[[0, 0],
[0, 0]],
[[0, 0],
[0, 0]],
[[0, 0],
[0, 0]]],
[[[0, 0],
[0, 0]],
[[0, 0],
[0, 0]],
[[0, 0],
[0, 0]],
[[0, 0],
[0, 0]],
[[0, 0],
[0, 0]]],
[[[0, 0],
[0, 0]],
[[0, 0],
[0, 0]],
[[0, 0],
[0, 0]],
[[0, 0],
[0, 0]],
[[0, 0],
[0, 0]]],
[[[0, 0],
[0, 0]],
[[0, 0],
[0, 0]],
[[0, 0],
[0, 0]],
[[0, 0],
[0, 0]],
[[0, 0],
[0, 0]]]], dtype=int16)
>>> a.shape
(4, 5, 2, 2)
>>>
Because shape is a tuple, you can access the length of an individual axis by index.
>>> a.shape
(4, 5, 2, 2)
>>> a.shape[1]
5
>>> a.shape[2]
2
import numpy as np
array = np.zeros((3, 4), dtype=np.int16)
print("Shape:", array.shape)
print("Dimensions:", array.ndim)
print("Elements:", array.size)
print("Data type:", array.dtype)
print("Bytes per element:", array.itemsize)
Shape: (3, 4)
Dimensions: 2
Elements: 12
Data type: int16
Bytes per element: 2
Index and Slice NumPy Arrays
NumPy uses zero-based indexing. In a one-dimensional array, one index selects one element. In a two-dimensional array, a row index and column index can be separated by a comma.
import numpy as np
values = np.array([10, 20, 30, 40, 50])
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(values[0])
print(values[-1])
print(values[1:4])
print(matrix[1, 2])
print(matrix[:, 1])
10
50
[20 30 40]
6
[2 5]
The expression matrix[:, 1] selects every row from column index 1. The colon means that all positions along that axis are included.
Understand NumPy Views and Copies
Basic slicing often returns a view that shares data with the original array. Changing the view may therefore change the source array. Call copy() when an independent array is required.
import numpy as np
original = np.array([10, 20, 30, 40])
view = original[1:3]
view[0] = 99
independent = original[1:3].copy()
independent[0] = -1
print(original)
print(view)
print(independent)
[10 99 30 40]
[99 30]
[-1 30]
Filter NumPy Arrays with Boolean Conditions
A comparison applied to an array produces a Boolean array of the same shape. Each Boolean value records whether the corresponding element satisfies the condition.
In the archived example below, the expression used is a<5, so the result marks elements that are less than 5.
>>> a = np.random.randint(1,8,20).reshape(4,5)
>>> a
array([[1, 5, 5, 7, 7],
[5, 5, 5, 6, 4],
[4, 5, 2, 2, 1],
[6, 6, 7, 4, 6]])
>>> b = a<5
>>> b
array([[ True, False, False, False, False],
[False, False, False, False, True],
[ True, False, True, True, True],
[False, False, False, True, False]])
>>>
The Boolean array can itself be used as a mask to select matching values.
import numpy as np
values = np.array([12, 3, 18, 7, 25, 4])
mask = values >= 10
print(mask)
print(values[mask])
[ True False True False True False]
[12 18 25]
Use & for element-wise AND, | for element-wise OR, and ~ for element-wise NOT. Place each comparison inside parentheses.
selected = values[(values >= 10) & (values < 20)]
print(selected)
[12 18]
Perform Element-Wise Arithmetic on NumPy Arrays
Arithmetic operators are applied element by element. For an array named a, a / 4 divides every element by 4, while a * 3 multiplies every element by 3.
The following example adds 4 to every array element.
>>> a = np.random.randint(1,8,20).reshape(4,5)
>>> a
array([[1, 4, 2, 7, 1],
[6, 2, 3, 7, 3],
[4, 7, 7, 5, 7],
[1, 2, 4, 4, 6]])
>>> a+4
array([[ 5, 8, 6, 11, 5],
[10, 6, 7, 11, 7],
[ 8, 11, 11, 9, 11],
[ 5, 6, 8, 8, 10]])
>>>
An expression such as a + 4 returns a new result and does not replace a. An augmented assignment such as a += 4 updates the existing array when the calculation can be represented by its current data type.
>>> a = np.random.randint(1,8,20).reshape(4,5)
>>> a
array([[1, 4, 2, 7, 1],
[6, 2, 3, 7, 3],
[4, 7, 7, 5, 7],
[1, 2, 4, 4, 6]])
>>> a+4
array([[ 5, 8, 6, 11, 5],
[10, 6, 7, 11, 7],
[ 8, 11, 11, 9, 11],
[ 5, 6, 8, 8, 10]])
>>> a
array([[1, 4, 2, 7, 1],
[6, 2, 3, 7, 3],
[4, 7, 7, 5, 7],
[1, 2, 4, 4, 6]])
>>> a += 4
>>> a
array([[ 5, 8, 6, 11, 5],
[10, 6, 7, 11, 7],
[ 8, 11, 11, 9, 11],
[ 5, 6, 8, 8, 10]])
>>>
Distinguish Element-Wise Multiplication from Matrix Multiplication
For two arrays of compatible shapes, * multiplies corresponding elements. The @ operator performs matrix multiplication.
import numpy as np
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
print(a * b)
print(a @ b)
[[ 5 12]
[21 32]]
[[19 22]
[43 50]]
Use NumPy Broadcasting with Compatible Shapes
Broadcasting allows NumPy to combine arrays of different but compatible shapes without manually repeating data. Shape comparison starts from the final axis. Two axis lengths are compatible when they are equal or when one of them is 1.
import numpy as np
matrix = np.array([[10, 20, 30],
[40, 50, 60]])
offsets = np.array([1, 2, 3])
result = matrix + offsets
print(result)
[[11 22 33]
[41 52 63]]
The offset array has shape (3,), which is compatible with the final axis of the matrix’s shape, (2, 3). A shape mismatch produces a broadcasting error rather than silently changing the data.
Calculate NumPy Sums, Means, and Axis-Based Statistics
NumPy includes aggregation functions for totals, averages, minimums, maximums, medians, standard deviations, and related calculations. Many of these functions accept an axis argument.
Calculate a Sum with numpy.sum()
numpy.sum() can add every element or reduce values along a specified axis.
>>> a = np.array([[1, 2], [3, 4]])
>>> np.sum(a)
10
>>> np.sum(a, axis=0)
array([4, 6])
>>> np.sum(a, axis=1)
array([3, 7])
For a two-dimensional array, axis=0 reduces the row axis and returns one result per column. axis=1 reduces the column axis and returns one result per row.
Calculate an Average with numpy.mean()
numpy.mean() returns the arithmetic mean of the complete array or the means calculated along one axis.
>>> a = np.array([[1, 2], [3, 4]])
>>> np.mean(a)
2.5
>>> np.mean(a, axis=0)
array([ 2., 3.])
>>> np.mean(a, axis=1)
array([ 1.5, 3.5])
The same axis rules apply to functions such as min(), max(), median(), and std().
import numpy as np
scores = np.array([[72, 80, 91],
[65, 88, 79],
[90, 92, 85]])
print("Column means:", scores.mean(axis=0))
print("Row maximums:", scores.max(axis=1))
print("Overall median:", np.median(scores))
Column means: [75.66666667 86.66666667 85. ]
Row maximums: [91 88 92]
Overall median: 85.0
Combine, Split, and Flatten NumPy Arrays
NumPy can join arrays along existing or new axes. Common functions include concatenate(), stack(), vstack(), and hstack().
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(np.concatenate((a, b)))
print(np.stack((a, b)))
print(np.vstack((a, b)))
[1 2 3 4 5 6]
[[1 2 3]
[4 5 6]]
[[1 2 3]
[4 5 6]]
Use ravel() or flatten() to convert a multidimensional array to one dimension. ravel() returns a view when possible, whereas flatten() returns a copy.
matrix = np.array([[1, 2], [3, 4]])
print(matrix.ravel())
print(matrix.flatten())
[1 2 3 4]
[1 2 3 4]
Sort NumPy Arrays and Find Unique Values
Use np.sort() to return sorted values and np.unique() to remove duplicates. np.unique() can also return occurrence counts.
import numpy as np
values = np.array([4, 2, 7, 2, 4, 4, 1])
unique_values, counts = np.unique(values, return_counts=True)
print(np.sort(values))
print(unique_values)
print(counts)
[1 2 2 4 4 4 7]
[1 2 4 7]
[1 2 3 1]
Handle Missing Floating-Point Values with NaN
Floating-point arrays may use np.nan to represent a missing or undefined numerical value. An ordinary aggregation can then return nan. NumPy provides NaN-aware functions such as np.nansum(), np.nanmean(), and np.nanmax().
import numpy as np
values = np.array([10.0, np.nan, 30.0])
print(np.mean(values))
print(np.nanmean(values))
print(np.isnan(values))
nan
20.0
[False True False]
np.nan is a floating-point value. Assigning it directly to an integer array is therefore not a general method for representing missing integers.
Save and Load NumPy Arrays
Use np.save() and np.load() for NumPy’s binary .npy format. Use np.savetxt() and np.loadtxt() when a plain-text format such as CSV is required.
import numpy as np
array = np.array([[10, 20], [30, 40]])
np.save("values.npy", array)
loaded_binary = np.load("values.npy")
np.savetxt("values.csv", array, delimiter=",", fmt="%d")
loaded_text = np.loadtxt("values.csv", delimiter=",", dtype=int)
print(loaded_binary)
print(loaded_text)
The binary format preserves NumPy array metadata such as shape and data type more directly. Text formats are easier to inspect in other programs but require suitable delimiter and type settings when loaded.
Run NumPy Examples in Jupyter Notebook
A Jupyter Notebook is useful for learning NumPy because code, output, notes, and visualizations can be kept in separate cells. Install Jupyter when it is not already available, and then start the notebook interface from the project directory.
python -m pip install jupyter
jupyter notebook
In the first notebook cell, import NumPy and verify the active environment.
import numpy as np
print(np.__version__)
If a notebook cannot import a package that works in the terminal, the notebook may be using a different Python environment or kernel.
Common NumPy Beginner Errors
- Using
arrangeinstead ofarange: the function is namednp.arange(). - Expecting the stop value in
arange(): the stop value is normally excluded. - Reshaping to an incompatible size: the product of the target dimensions must equal the number of elements.
- Confusing
*and@:*is element-wise multiplication, while@is matrix multiplication. - Using Python’s
andororwith array conditions: use&and|, with each comparison in parentheses. - Changing a slice unintentionally: a basic slice may share memory with the original array; use
copy()for independent data. - Ignoring integer overflow or precision loss: confirm that the selected
dtypecan represent the required values. - Installing NumPy into the wrong environment: run pip through the same Python interpreter that executes the program.
Suggested NumPy Learning Path for Beginners
- Review basic Python lists, indexing, slicing, functions, and imports.
- Learn
np.array(),arange(),linspace(),zeros(), andones(). - Practice
shape,size,ndim,dtype, andreshape(). - Practice indexing, slicing, Boolean masks, and copies.
- Learn element-wise arithmetic, broadcasting, and axis-based aggregation.
- Continue with sorting, joining, random generation, file input and output, and linear algebra as required by your projects.
NumPy is easier to learn when each concept is tested with small arrays whose results can be checked manually. After the basics are clear, apply the same operations to a small dataset in a Python script or Jupyter Notebook.
NumPy Function Reference and Further Reading
The archived function index previously used by this tutorial is available at https://docs.scipy.org/doc/numpy-1.15.0/genindex.html. Because that index documents an older release, use the current stable NumPy documentation when checking present-day behavior and available APIs.
The official NumPy absolute beginner’s guide is also useful after completing the examples on this page.
Python Examples for Frequently Used NumPy Functions
Python NumPy Tutorial FAQs
Is NumPy easy to learn?
NumPy’s basic array operations are generally approachable after you understand Python lists, indexing, slicing, functions, and imports. Broadcasting, multidimensional indexing, data-type conversion, views, and axis-based operations usually require additional practice.
Should I learn Python before learning NumPy?
Yes. Learn core Python syntax first, including variables, lists, loops, conditions, functions, modules, and exceptions. You do not need to master every part of Python before starting NumPy, but the fundamentals make NumPy examples easier to understand.
How long does it take to learn NumPy?
The time depends on your Python experience and the depth required. A learner can understand basic array creation, indexing, reshaping, and arithmetic through focused practice, while advanced broadcasting, linear algebra, performance analysis, and integration with scientific libraries take longer.
What is the difference between a NumPy array and a Python list?
A Python list is a general-purpose container that may hold values of different types. A NumPy array normally uses one data type and supports multidimensional indexing, vectorized arithmetic, broadcasting, and numerical aggregation directly.
Can I learn NumPy in a Jupyter Notebook?
Yes. A Jupyter Notebook is suitable for NumPy practice because each code cell can be executed independently and its output appears directly below it. The same NumPy code can also be placed in ordinary .py files.
NumPy Tutorial Editorial QA Checklist
- Confirm that installation commands distinguish a basic NumPy installation from optional scientific and Jupyter packages.
- Run new Python examples with the supported Python and NumPy versions before publishing changes.
- Verify that each displayed output matches its corresponding NumPy code.
- Check every explanation of
axis=0,axis=1, broadcasting, and reshape compatibility against the example’s actual shape. - Keep archived installation output clearly identified so readers do not treat old package versions as current requirements.
- Review integer ranges, floating-point precision statements, and type-conversion examples for possible overflow or data loss.
- Confirm that links to NumPy reference material point to the current stable documentation unless an older version is intentionally being discussed.
TutorialKart.com