NumPy is one of the most important Python libraries for working with numbers, arrays, matrices, and scientific calculations.
The name NumPy stands for:
Numerical Python
It is widely used in:
- Data science
- Machine learning
- Artificial intelligence
- Scientific computing
- Engineering
- Statistics
- Financial analysis
- Image processing
- Numerical simulations
If you are learning Python for AI, machine learning, or data science, NumPy is one of the first libraries you should understand.
A simple NumPy example looks like this:
import numpy as np
numbers = np.array([10, 20, 30, 40])
print(numbers)
Output:
[10 20 30 40]
The most important feature of NumPy is its powerful array object, called ndarray.
Why Is NumPy Used?
Python already provides lists:
numbers = [10, 20, 30, 40]
So why do developers need NumPy?
Because NumPy provides specialized data structures and mathematical operations designed for numerical computing.
For example, with normal Python lists:
numbers = [1, 2, 3, 4]
result = []
for number in numbers:
result.append(number * 2)
print(result)
Output:
[2, 4, 6, 8]
With NumPy:
import numpy as np
numbers = np.array([1, 2, 3, 4])
result = numbers * 2
print(result)
Output:
[2 4 6 8]
NumPy allows mathematical operations to be applied directly across entire arrays.
This makes numerical code:
- Shorter
- Easier to read
- More efficient
- Better suited for large datasets
What Is a NumPy Array?
The main data structure in NumPy is called:
ndarray
It means:
N-dimensional array
A NumPy array can contain numbers arranged in one or more dimensions.
One-Dimensional Array
import numpy as np
numbers = np.array([10, 20, 30, 40])
print(numbers)
Output:
[10 20 30 40]
This is a one-dimensional array.
You can think of it like:
10 20 30 40
Two-Dimensional NumPy Array
A two-dimensional array looks similar to a table or matrix.
import numpy as np
numbers = np.array([
[1, 2, 3],
[4, 5, 6]
])
print(numbers)
Output:
[[1 2 3]
[4 5 6]]
You can visualize it as:
1 2 3
4 5 6
This type of structure is commonly used in:
- Machine learning
- Matrix mathematics
- Image processing
- Data analysis
Three-Dimensional NumPy Array
NumPy can also create arrays with more dimensions.
Example:
import numpy as np
data = np.array([
[
[1, 2],
[3, 4]
],
[
[5, 6],
[7, 8]
]
])
print(data)
This is a three-dimensional array.
NumPy is not limited to three dimensions.
It can work with higher-dimensional arrays as well.
How to Install NumPy
NumPy is not part of the basic Python language, so it normally needs to be installed separately.
Using pip:
pip install numpy
Depending on your environment, you may use:
python -m pip install numpy
After installation, you can check it with:
import numpy
print(numpy.__version__)
How to Import NumPy
The most common way to import NumPy is:
import numpy as np
Here:
numpy
is the library name.
And:
np
is an alias.
Using np is a widely used convention.
Instead of:
numpy.array([1, 2, 3])
you can write:
np.array([1, 2, 3])
Creating Your First NumPy Array
Use:
np.array()
Example:
import numpy as np
numbers = np.array([5, 10, 15, 20])
print(numbers)
Output:
[ 5 10 15 20]
NumPy Array vs Python List
Python lists and NumPy arrays may look similar, but they are designed for different purposes.
| Feature | Python List | NumPy Array |
|---|---|---|
| General-purpose storage | Excellent | Mainly numerical |
| Mathematical operations | Limited | Excellent |
| Multidimensional data | Possible but less convenient | Built-in support |
| Memory efficiency | Lower for many numeric workloads | Often better |
| Vectorized calculations | No | Yes |
| Scientific computing | Limited | Excellent |
| Matrix operations | Manual or extra libraries | Built in |
For ordinary collections, Python lists are perfectly fine.
For heavy numerical calculations, NumPy is usually more suitable.
NumPy Data Types
NumPy arrays have a specific data type.
Example:
import numpy as np
numbers = np.array([1, 2, 3, 4])
print(numbers.dtype)
You may see a result such as:
int64
The exact integer size can depend on the platform.
Common NumPy data types include:
int8
int16
int32
int64
float32
float64
bool
complex64
complex128
Creating an Array With a Specific Data Type
You can specify the type using:
dtype
Example:
import numpy as np
numbers = np.array([1, 2, 3], dtype=np.float64)
print(numbers)
Output:
[1. 2. 3.]
Check the type:
print(numbers.dtype)
Array Dimensions
You can check the number of dimensions using:
ndim
Example:
import numpy as np
numbers = np.array([
[1, 2],
[3, 4]
])
print(numbers.ndim)
Output:
2
NumPy Array Shape
The shape property tells you the size of each dimension.
Example:
import numpy as np
numbers = np.array([
[1, 2, 3],
[4, 5, 6]
])
print(numbers.shape)
Output:
(2, 3)
This means:
2 rows
3 columns
Array Size
Use:
size
to find the total number of elements.
Example:
print(numbers.size)
Output:
6
Because the array contains:
2 × 3 = 6
elements.
Accessing NumPy Array Elements
NumPy uses indexing.
Example:
import numpy as np
numbers = np.array([10, 20, 30, 40])
print(numbers[0])
Output:
10
Indexes begin at:
0
So:
numbers[0] → 10
numbers[1] → 20
numbers[2] → 30
numbers[3] → 40
Negative Indexing
Negative indexes access elements from the end.
numbers = np.array([10, 20, 30, 40])
print(numbers[-1])
Output:
40
Accessing 2D Array Elements
For a two-dimensional array:
numbers = np.array([
[1, 2, 3],
[4, 5, 6]
])
You can access an element with:
print(numbers[1, 2])
Output:
6
Here:
1 → second row
2 → third column
NumPy Array Slicing
Slicing allows you to select part of an array.
Example:
import numpy as np
numbers = np.array([10, 20, 30, 40, 50])
print(numbers[1:4])
Output:
[20 30 40]
The general syntax is:
array[start:end]
The ending index is not included.
Slicing From the Beginning
print(numbers[:3])
Output:
[10 20 30]
Slicing to the End
print(numbers[2:])
Output:
[30 40 50]
Creating Arrays With zeros()
NumPy can create an array filled with zeros.
import numpy as np
numbers = np.zeros(5)
print(numbers)
Output:
[0. 0. 0. 0. 0.]
A 2D example:
matrix = np.zeros((2, 3))
print(matrix)
Output:
[[0. 0. 0.]
[0. 0. 0.]]
Creating Arrays With ones()
Use:
np.ones()
Example:
numbers = np.ones(4)
print(numbers)
Output:
[1. 1. 1. 1.]
Creating a Range With arange()
NumPy provides:
np.arange()
Example:
numbers = np.arange(0, 10)
print(numbers)
Output:
[0 1 2 3 4 5 6 7 8 9]
You can also specify a step:
numbers = np.arange(0, 10, 2)
print(numbers)
Output:
[0 2 4 6 8]
Creating Evenly Spaced Values With linspace()
linspace() creates a specified number of evenly spaced values between two points.
Example:
import numpy as np
numbers = np.linspace(0, 10, 5)
print(numbers)
Output:
[ 0. 2.5 5. 7.5 10. ]
This is useful in:
- Scientific calculations
- Graphs
- Simulations
Basic NumPy Arithmetic
NumPy makes array mathematics simple.
Example:
import numpy as np
numbers = np.array([1, 2, 3, 4])
print(numbers + 10)
Output:
[11 12 13 14]
Multiplication
print(numbers * 2)
Output:
[2 4 6 8]
Subtraction
print(numbers - 1)
Output:
[0 1 2 3]
Division
print(numbers / 2)
Output:
[0.5 1. 1.5 2. ]
Operations Between Two Arrays
You can perform element-by-element calculations.
Example:
a = np.array([1, 2, 3])
b = np.array([10, 20, 30])
print(a + b)
Output:
[11 22 33]
Multiplication:
print(a * b)
Output:
[10 40 90]
This is element-wise multiplication.
What Is Vectorization?
Vectorization is one of NumPy’s most important concepts.
Instead of manually looping over every element:
result = []
for number in numbers:
result.append(number * 2)
NumPy allows:
result = numbers * 2
This is called a vectorized operation.
Vectorized code is usually:
- Cleaner
- Shorter
- Easier to understand
- Faster for many numerical operations
NumPy Mathematical Functions
NumPy provides many mathematical functions.
Example array:
numbers = np.array([1, 4, 9, 16])
Square root:
print(np.sqrt(numbers))
Output:
[1. 2. 3. 4.]
Sum
numbers = np.array([10, 20, 30])
print(np.sum(numbers))
Output:
60
Mean
print(np.mean(numbers))
Output:
20.0
Minimum Value
print(np.min(numbers))
Output:
10
Maximum Value
print(np.max(numbers))
Output:
30
Standard Deviation
NumPy can calculate standard deviation:
print(np.std(numbers))
This is useful in statistics and data science.
Reshaping NumPy Arrays
You can change an array’s shape using:
reshape()
Example:
import numpy as np
numbers = np.array([1, 2, 3, 4, 5, 6])
matrix = numbers.reshape(2, 3)
print(matrix)
Output:
[[1 2 3]
[4 5 6]]
The original six values are now arranged into:
2 rows × 3 columns
Flattening an Array
A multidimensional array can be converted into one dimension.
Example:
matrix = np.array([
[1, 2],
[3, 4]
])
flat = matrix.flatten()
print(flat)
Output:
[1 2 3 4]
NumPy Array Transpose
Transposing switches rows and columns.
Example:
matrix = np.array([
[1, 2, 3],
[4, 5, 6]
])
print(matrix.T)
Output:
[[1 4]
[2 5]
[3 6]]
Transpose operations are very common in linear algebra and machine learning.
Filtering NumPy Arrays
You can filter data using conditions.
Example:
numbers = np.array([10, 20, 30, 40, 50])
result = numbers[numbers > 25]
print(result)
Output:
[30 40 50]
This is known as boolean indexing.
Multiple Conditions
You can combine conditions.
Example:
result = numbers[(numbers > 20) & (numbers < 50)]
print(result)
Output:
[30 40]
With NumPy arrays, use operators such as & and | with properly parenthesized conditions rather than Python’s normal and and or for element-wise comparisons.
Sorting NumPy Arrays
Use:
np.sort()
Example:
numbers = np.array([40, 10, 30, 20])
sorted_numbers = np.sort(numbers)
print(sorted_numbers)
Output:
[10 20 30 40]
Combining NumPy Arrays
You can concatenate arrays.
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
result = np.concatenate((a, b))
print(result)
Output:
[1 2 3 4 5 6]
NumPy Random Numbers
NumPy provides random-number functionality that is useful for:
- Simulations
- Testing
- Machine learning
- Statistics
A modern approach is to create a random generator:
import numpy as np
rng = np.random.default_rng()
numbers = rng.random(5)
print(numbers)
This produces random floating-point values.
Random Integers
rng = np.random.default_rng()
numbers = rng.integers(1, 10, size=5)
print(numbers)
The values will vary each time.
Matrix Operations in NumPy
NumPy is frequently used for matrix calculations.
Example:
a = np.array([
[1, 2],
[3, 4]
])
b = np.array([
[5, 6],
[7, 8]
])
Element-wise multiplication:
print(a * b)
Matrix multiplication:
print(a @ b)
These are different operations.
That distinction is especially important in machine learning and linear algebra.
Dot Product
NumPy also provides:
np.dot()
Example:
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
result = np.dot(a, b)
print(result)
Output:
32
Because:
1×4 + 2×5 + 3×6
=
4 + 10 + 18
=
32
Broadcasting in NumPy
Broadcasting allows NumPy to perform operations between arrays with compatible but different shapes.
Simple example:
numbers = np.array([1, 2, 3])
print(numbers + 10)
NumPy behaves conceptually like:
[1, 2, 3]
+
[10, 10, 10]
Result:
[11 12 13]
The scalar 10 is effectively applied across the array.
Broadcasting With a Matrix
Example:
matrix = np.array([
[1, 2, 3],
[4, 5, 6]
])
values = np.array([10, 20, 30])
print(matrix + values)
Output:
[[11 22 33]
[14 25 36]]
Broadcasting is very powerful but requires compatible shapes.
NumPy Axis
The axis parameter tells NumPy which direction to operate along.
Consider:
matrix = np.array([
[1, 2, 3],
[4, 5, 6]
])
Total sum:
print(np.sum(matrix))
Output:
21
Column-wise sum:
print(np.sum(matrix, axis=0))
Output:
[5 7 9]
Row-wise sum:
print(np.sum(matrix, axis=1))
Output:
[ 6 15]
Understanding axes becomes very important when working with multidimensional data.
NumPy Copy vs View
This is an important beginner concept.
Some NumPy operations create a view instead of completely copying the underlying data.
For example:
numbers = np.array([10, 20, 30, 40])
view = numbers[1:3]
view[0] = 99
print(numbers)
The original array may also change because the slice can reference the same underlying data.
Output:
[10 99 30 40]
If you need an independent copy:
copy = numbers[1:3].copy()
Understanding this helps avoid unexpected changes.
NumPy and Machine Learning
NumPy is extremely important for understanding machine learning.
A dataset can often be represented conceptually as:
Rows → Samples
Columns → Features
For example:
data = np.array([
[25, 50000],
[30, 65000],
[35, 80000]
])
This could represent:
Age | Salary
25 | 50000
30 | 65000
35 | 80000
Machine learning heavily relies on:
- Arrays
- Vectors
- Matrices
- Linear algebra
- Statistics
NumPy teaches these foundations.
NumPy and Artificial Intelligence
AI systems frequently work with numerical data.
For example:
Image
↓
Pixel Numbers
↓
Array / Tensor
↓
AI Model
An image can be represented as a multidimensional array of pixel values.
Similarly:
Audio → Numerical samples
Text → Numerical tokens/embeddings
Video → Multidimensional numerical data
This is one reason array programming is so important in AI.
NumPy vs pandas
NumPy and pandas are related but serve different purposes.
| NumPy | pandas |
|---|---|
| Numerical arrays | Tabular data |
ndarray | DataFrame and Series |
| Matrix operations | Data cleaning and analysis |
| Numerical computing | Business/data analysis |
| Lower-level foundation | Often built on NumPy concepts |
For pure numerical operations, NumPy is usually more direct.
For spreadsheet-like datasets with named columns, pandas is often easier.
NumPy vs Python Lists
Use Python lists when:
- You have mixed data types
- You need a general-purpose collection
- Your dataset is small
- Advanced mathematical operations are unnecessary
Use NumPy when:
- You have large numerical datasets
- You need vectorized operations
- You need matrix calculations
- You are learning ML or data science
- Performance matters for numerical processing
NumPy vs Tensor Libraries
NumPy arrays are often compared with tensors used by frameworks such as:
- PyTorch
- TensorFlow
- JAX
They share many concepts:
Shape
Dimensions
Indexing
Broadcasting
Vectorization
Matrix Operations
Learning NumPy makes these frameworks easier to understand.
Why Is NumPy Faster Than Normal Python for Many Numerical Tasks?
NumPy is optimized specifically for numerical operations.
Rather than running a Python-level loop for every element, many NumPy operations execute optimized native routines underneath.
This allows an operation such as:
numbers * 2
to process large arrays efficiently.
However, NumPy is not automatically faster for every possible task.
Its biggest advantage appears in operations that can be expressed using NumPy’s optimized array operations.
Simple NumPy Performance Example
Normal Python:
numbers = list(range(1000000))
result = []
for number in numbers:
result.append(number * 2)
NumPy:
import numpy as np
numbers = np.arange(1000000)
result = numbers * 2
The NumPy version is also much shorter and easier to read.
NumPy Memory Efficiency
A Python list contains references to Python objects.
NumPy arrays usually store homogeneous numerical values in a compact contiguous or regularly strided memory representation.
This can reduce memory overhead for large numerical datasets.
For example:
numbers = np.array([1, 2, 3, 4], dtype=np.int32)
Each element uses a defined numeric representation.
This predictability is useful for high-performance numerical computing.
Common Beginner NumPy Mistakes
1. Forgetting to Import NumPy
Incorrect:
numbers = np.array([1, 2, 3])
without importing NumPy first.
Correct:
import numpy as np
2. Confusing Lists With Arrays
Python:
numbers = [1, 2, 3]
NumPy:
numbers = np.array([1, 2, 3])
They are different data structures.
3. Expecting List Multiplication to Behave Like NumPy
Python list:
numbers = [1, 2, 3]
print(numbers * 2)
Output:
[1, 2, 3, 1, 2, 3]
NumPy array:
numbers = np.array([1, 2, 3])
print(numbers * 2)
Output:
[2 4 6]
This is a very important difference.
4. Confusing Element-Wise and Matrix Multiplication
a * b
performs element-wise multiplication.
a @ b
performs matrix multiplication when the shapes are compatible.
5. Ignoring Array Shape
Always inspect:
array.shape
when working with multidimensional data.
Many NumPy errors happen because array shapes do not match.
6. Misunderstanding Broadcasting
Arrays cannot always be combined simply because they contain numbers.
Their shapes must be compatible with NumPy’s broadcasting rules.
7. Modifying a View Accidentally
Slicing an array can produce a view.
If you need independent data, explicitly use:
.copy()
Useful NumPy Properties
Assume:
numbers = np.array([
[1, 2, 3],
[4, 5, 6]
])
Useful properties include:
numbers.ndim
Number of dimensions.
numbers.shape
Shape of the array.
numbers.size
Total elements.
numbers.dtype
Data type.
Useful NumPy Functions for Beginners
Some important functions include:
np.array()
np.zeros()
np.ones()
np.arange()
np.linspace()
np.reshape()
np.sum()
np.mean()
np.min()
np.max()
np.sqrt()
np.sort()
np.concatenate()
np.dot()
You do not need to memorize every NumPy function.
Learn the fundamental array concepts first.
Beginner NumPy Example
Here is a small program:
import numpy as np
scores = np.array([75, 85, 90, 65, 95])
print("Scores:", scores)
print("Average:", np.mean(scores))
print("Highest:", np.max(scores))
print("Lowest:", np.min(scores))
Output:
Scores: [75 85 90 65 95]
Average: 82.0
Highest: 95
Lowest: 65
This demonstrates how easily NumPy can analyze numerical data.
Another Example: Student Marks
import numpy as np
marks = np.array([
[80, 90, 85],
[70, 75, 80],
[90, 95, 92]
])
print("All marks:")
print(marks)
print("Average mark:")
print(np.mean(marks))
You can also calculate each student’s average:
print(np.mean(marks, axis=1))
NumPy Learning Roadmap
A good beginner learning order is:
Install NumPy
↓
Create Arrays
↓
Dimensions and Shapes
↓
Indexing
↓
Slicing
↓
Data Types
↓
Array Operations
↓
Vectorization
↓
Filtering
↓
Reshaping
↓
Broadcasting
↓
Statistics
↓
Linear Algebra
After that, you can move into:
pandas
Matplotlib
scikit-learn
PyTorch
TensorFlow
depending on your goals.
NumPy for AI/ML Beginners
If your goal is becoming an AI or machine learning developer, focus especially on:
- Arrays
- Shapes
- Indexing
- Slicing
- Broadcasting
- Vectorization
- Matrix multiplication
- Mean and standard deviation
- Reshaping
- Transposing
- Boolean indexing
These concepts appear repeatedly in ML frameworks.
Simple NumPy Practice Projects
After learning the basics, try building:
- Student marks analyzer
- Temperature statistics program
- Expense analyzer
- Matrix calculator
- Sales data analyzer
- Random number simulator
- Basic image-array experiment
- Linear algebra practice program
These small projects help you understand NumPy much faster than only reading syntax.
Frequently Asked Questions
What is NumPy?
NumPy is a Python library for numerical computing. It provides powerful multidimensional arrays and mathematical functions.
What does NumPy stand for?
NumPy stands for:
Numerical Python
Is NumPy built into Python?
No. It normally needs to be installed separately.
pip install numpy
How do I import NumPy?
The standard convention is:
import numpy as np
What is ndarray?
ndarray is NumPy’s main multidimensional array data structure.
Is NumPy faster than Python lists?
For many large numerical and vectorized operations, NumPy can be significantly more efficient than equivalent Python-level loops. But it is not automatically faster for every type of task.
Is NumPy used in AI?
Yes. NumPy is widely used for numerical computing and teaches many array, matrix, and vector concepts used throughout AI and machine learning.
Is NumPy used in machine learning?
Yes. Even when ML frameworks use their own tensor objects, NumPy concepts such as dimensions, shape, broadcasting, and vectorization remain highly relevant.
Should I learn NumPy before pandas?
For data science, learning NumPy basics first is highly useful because it makes pandas and other numerical tools easier to understand.
Should I learn NumPy before machine learning?
Yes. A solid understanding of NumPy can make machine learning significantly easier because ML relies heavily on numerical arrays and matrix operations.
Is NumPy difficult for beginners?
The basics are straightforward. Concepts such as broadcasting, multidimensional axes, advanced indexing, and linear algebra may require more practice.
Final Thoughts
NumPy is one of the foundational libraries in the Python ecosystem.
At its core, NumPy helps you work efficiently with:
Numbers
↓
Arrays
↓
Vectors
↓
Matrices
↓
Large Numerical Datasets
A basic NumPy workflow looks like:
import numpy as np
numbers = np.array([10, 20, 30, 40])
print(np.mean(numbers))
Output:
25.0
The most important concepts to understand first are:
Arrays → Dimensions → Shapes → Indexing → Slicing → Vectorization → Broadcasting → Matrix Operations
If your goal is AI, machine learning, data science, or scientific computing, NumPy is an essential library to learn because it provides the numerical foundation behind many of the concepts you will use later.




