Python NumPy Tutorial: Learn Python Numpy With Examples
By Rohit Sharma
Updated on Oct 09, 2025 | 11 min read | 7.44K+ views
Share:
For working professionals
For fresh graduates
More
By Rohit Sharma
Updated on Oct 09, 2025 | 11 min read | 7.44K+ views
Share:
Table of Contents
NumPy is the core library for numerical computing in Python. It provides fast, efficient, and flexible tools for handling large datasets. With NumPy, you can perform complex mathematical operations, manipulate arrays, and streamline data processing tasks. It is essential for data analysis, scientific computing, and machine learning workflows.
In this guide, you'll read more about NumPy in Python. We'll cover what NumPy is, why it’s important, and how to install it. You’ll learn array creation, indexing, and slicing. We’ll explore mathematical, statistical, and linear algebra operations. Advanced topics like broadcasting, boolean indexing, and random number generation will also be included.
Explore data science online courses from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.
Popular Data Science Programs
Before you start exploring NumPy, you need to install it. This step is essential in any python numpy tutorial because NumPy is not included in the default Python setup. Installing it is quick and beginner-friendly.
NumPy works with Python 3.x versions. To verify your version, open your terminal or command prompt and type:
python --version
If your version is 3.x, you can proceed. Otherwise, install or upgrade Python from the official Python website.
Begin your data science journey with upGrad’s industry-aligned programs. Learn from leading experts, master essential tools and techniques, and build job-ready skills through hands-on projects and real-world applications.
The easiest way to install NumPy in Python is with pip. This step is key in any numpy in python tutorial.
pip install numpy
import numpy as np
print(np.__version__)
You should see the installed NumPy version.
A virtual environment helps manage packages without affecting system Python. Steps:
python -m venv myenv
OS |
Command |
Windows | myenv\Scripts\activate |
macOS/Linux | source myenv/bin/activate |
pip install numpy
deactivate
Using virtual environments is best practice in any numpy tutorial in python.
Also Read: How to Install Python on macOS
For users of Anaconda, NumPy comes pre-installed. Update it using:
conda update numpy
Or create a new environment with NumPy:
conda create -n myenv numpy
conda activate myenv
Check that NumPy is ready for use by running:
import numpy as np
a = np.array([1, 2, 3])
print(a)
Output:
[1 2 3]
This confirms NumPy is installed and ready for your python numpy tutorial exercises.
Issue |
Solution |
pip not recognized | Ensure Python and pip are in your system PATH. |
Version conflict | Upgrade pip: pip install --upgrade pip |
Permission denied | Use pip install numpy --user or run terminal as admin |
pip install --upgrade numpy
Installing NumPy is a simple first step in any numpy tutorial in python. Once installed, you can move on to array operations, mathematical functions, and more advanced tasks efficiently.
Also Read: How to Install Python in Windows (Even If You're a Beginner!)
In this python numpy tutorial, the core concept you will work with is the NumPy array. Arrays are the foundation of NumPy and allow you to store and manipulate data efficiently. Unlike Python lists, NumPy arrays are faster, use less memory, and support advanced mathematical operations.
A NumPy array is called an ndarray (n-dimensional array). It can be:
Example:
import numpy as np
# 1D array
arr1 = np.array([1, 2, 3, 4, 5])
# 2D array
arr2 = np.array([[1, 2, 3], [4, 5, 6]])
NumPy provides several ways to create arrays:
Table: Array creation functions
Function |
Description |
Example |
np.array() | Convert list/tuple to array | np.array([1,2,3]) |
np.zeros() | Array of zeros | np.zeros(5) |
np.ones() | Array of ones | np.ones(3) |
np.arange() | Sequence of numbers | np.arange(0,10,2) |
np.linspace() | Evenly spaced values | np.linspace(0,1,5) |
Also Read: Python Array: Declaration, Operations, and NumPy Implementation Guide
Accessing elements in NumPy arrays is straightforward:
Examples:
arr = np.array([10, 20, 30, 40, 50])
print(arr[0]) # Output: 10
print(arr[1:4]) # Output: [20 30 40]
For 2D arrays, use row, column notation:
matrix = np.array([[1,2,3],[4,5,6]])
print(matrix[0,2]) # Output: 3
print(matrix[:,1]) # Output: [2 5]
Every NumPy array has a data type (dtype). It ensures consistency and faster computation.
Table: Common NumPy data types
dtype |
Description |
int32 | 32-bit integer |
float64 | 64-bit float |
bool | Boolean values |
complex128 | Complex numbers |
Example:
arr = np.array([1,2,3,4])
print(arr * 2) # Output: [2 4 6 8]
Summary:
NumPy arrays are the backbone of any python numpy tutorial. They let you store data in 1D, 2D, or 3D structures, perform fast computations, and manage data efficiently. Mastering array creation, indexing, slicing, and understanding data types will set a strong foundation for all further NumPy operations.
Also Read: Python AI Projects: Best 30 Artificial Intelligence Projects
Data Science Courses to upskill
Explore Data Science Courses for Career Progression
Once you understand NumPy arrays, the next step in any python numpy tutorial is performing operations on them. NumPy makes mathematical, statistical, and linear algebra operations simple and fast. You can apply operations element-wise without writing loops.
NumPy supports basic arithmetic on arrays:
Example:
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
print(arr1 + arr2) # Output: [5 7 9]
print(arr1 * 2) # Output: [2 4 6]
NumPy provides built-in functions to calculate statistics quickly:
Example:
arr = np.array([10, 20, 30, 40])
print(np.sum(arr)) # 100
print(np.mean(arr)) # 25.0
print(np.std(arr)) # 11.1803
Table: Common Statistical Functions
Function |
Description |
np.sum() | Sum of elements |
np.mean() | Average value |
np.median() | Middle value |
np.std() | Standard deviation |
np.min() / np.max() | Minimum / Maximum values |
Also Read: Arithmetic Operators in Python
NumPy makes linear algebra simple for vectors and matrices:
Example:
matrix1 = np.array([[1,2],[3,4]])
matrix2 = np.array([[5,6],[7,8]])
print(matrix1 + matrix2)
# Output: [[ 6 8]
# [10 12]]
print(np.dot(matrix1, matrix2))
# Output: [[19 22]
# [43 50]]
NumPy offers ufuncs that apply operations to each element of an array efficiently:
Example:
arr = np.array([1,4,9])
print(np.sqrt(arr)) # Output: [1. 2. 3.]
Table: Useful NumPy ufuncs
Function |
Description |
np.sqrt() | Square root |
np.exp() | Exponential of each element |
np.log() | Natural logarithm |
np.sin() | Sine of each element |
np.cos() | Cosine of each element |
Summary:
NumPy operations are at the heart of any python numpy tutorial. From basic arithmetic and statistics to matrix manipulations and ufuncs, these tools let you handle data efficiently. Mastering these operations will prepare you for data analysis, scientific computing, and machine learning tasks.
Also Read: Top 50 Python Project Ideas with Source Code in 2025
After learning basic NumPy operations, the next step in any python numpy tutorial is manipulating arrays. NumPy provides tools to reshape, join, split, and manage arrays efficiently. These techniques are essential for preparing data for analysis or machine learning.
You can change the shape of an array without altering its data.
Example:
arr = np.array([[1,2,3],[4,5,6]])
reshaped = arr.reshape(3,2)
print(reshaped)
# Output:
# [[1 2]
# [3 4]
# [5 6]]
Also Read: Pandas vs NumPy in Data Science: Top 15 Differences
NumPy lets you combine or divide arrays for flexibility.
Example:
a = np.array([1,2,3])
b = np.array([4,5,6])
joined = np.concatenate([a,b])
print(joined) # Output: [1 2 3 4 5 6]
Table: Joining and Splitting Functions
Function |
Purpose |
np.concatenate() | Join arrays along an axis |
np.vstack() | Stack arrays vertically |
np.hstack() | Stack arrays horizontally |
np.split() | Split array into sub-arrays |
Understanding the difference between a copy and a view is important in NumPy.
Example:
arr = np.array([1,2,3])
view = arr.view()
copy = arr.copy()
view[0] = 10
print(arr) # Output: [10 2 3]
copy[1] = 20
print(arr) # Output: [10 2 3] (unchanged)
Table: Copy vs View
Feature |
View |
Copy |
Shares memory | Yes | No |
Changes affect original | Yes | No |
Use case | Efficient memory | Independent array |
Also Read: Most Frequently Asked NumPy Interview Questions and Answers
Summary:
Array manipulation is a core topic in any python numpy tutorial. By mastering reshaping, joining, splitting, and understanding memory views, you can efficiently handle and preprocess data for analysis or machine learning. These skills make working with NumPy arrays flexible and error-free.
After learning arrays, operations, and manipulations, it’s important to see NumPy in action. In this section of our python numpy tutorial, we’ll explore practical examples that show how NumPy is used in real-world scenarios. These examples will help you understand why NumPy is a vital tool in data analysis, scientific computing, and machine learning.
NumPy is widely used to process and analyze numerical data. For example, if you have sales data for a week:
import numpy as np
sales = np.array([150, 200, 300, 250, 400, 500, 350])
print("Total sales:", np.sum(sales))
print("Average sales:", np.mean(sales))
print("Maximum sales:", np.max(sales))
Output:
Total sales: 2150
Average sales: 307.14
Maximum sales: 500
Use case: You can quickly calculate totals, averages, and other statistics for large datasets without loops.
Also Read: What is Data Analytics: Definition, Types, Applications & Challenges
Images are stored as multi-dimensional arrays, and NumPy makes it easy to manipulate them.
image = np.random.randint(0, 256, size=(5,5,3)) # Random 5x5 RGB image
print("Red channel:", image[:,:,0]) # Accessing red color values
Use case: NumPy is often combined with libraries like OpenCV or PIL to modify, filter, or analyze images efficiently.
Machine learning models require numeric data in arrays. NumPy helps transform raw data into structured arrays:
# Example: Height and weight data
height = np.array([150, 160, 170, 180])
weight = np.array([50, 60, 65, 80])
# Calculate Body Mass Index (BMI)
bmi = weight / (height/100)**2
print("BMI values:", bmi)
Output:
BMI values: [22.22 23.44 22.49 24.69]
Use case: NumPy allows you to perform batch calculations efficiently for training ML models.
Also Read: Top 48 Machine Learning Projects [2025 Edition] with Source Code
NumPy is commonly used in finance for tasks like analyzing stock prices or calculating returns:
prices = np.array([100, 102, 105, 103, 108])
returns = (prices[1:] - prices[:-1]) / prices[:-1]
print("Daily returns:", returns)
Output:
Daily returns: [0.02 0.02941176 -0.01904762 0.04854369]
Use case: Investors can quickly analyze trends and volatility in stock data.
NumPy arrays are essential for simulations in physics, chemistry, and engineering. For instance, generating points for a sine wave:
x = np.linspace(0, 2*np.pi, 10)
y = np.sin(x)
print("Sine values:", y)
Use case: Simulations, modeling, and experiments often rely on efficient array computations.
Mastering these applications is a key part of any python numpy tutorial. Once you practice these examples, you can handle almost any numerical data efficiently and effectively.
Working efficiently with NumPy is not just about knowing functions and operations. In this part of our python numpy tutorial, we’ll cover best practices that help you write clean, fast, and reliable code while avoiding common mistakes.
NumPy is optimized for vectorized operations, which means you should avoid Python loops for array computations.
Example:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
# Vectorized operation
arr_squared = arr ** 2
print(arr_squared) # Output: [ 1 4 9 16 25]
# Avoid using loops
arr_squared_loop = [x**2 for x in arr]
Why: Vectorized operations are faster and more memory-efficient, especially for large datasets.
Also Read: Python While Loop Statements: Explained With Examples
NumPy arrays support different data types (dtype). Choosing the right type improves performance and reduces memory usage.
Example:
arr = np.array([1, 2, 3], dtype=np.float32)
print(arr.dtype) # Output: float32
Table: Common Data Types and Memory Usage
dtype |
Description |
Memory per element |
int32 | 32-bit integer | 4 bytes |
float32 | 32-bit float | 4 bytes |
float64 | 64-bit float | 8 bytes |
bool | Boolean values | 1 byte |
NumPy arrays can create views or copies. Views save memory because they point to the same data. Copies consume extra memory.
Example:
arr = np.array([1, 2, 3])
view_arr = arr.view()
copy_arr = arr.copy()
Why: Efficient memory usage is critical when working with large datasets.
Contiguous arrays are stored in a single memory block. NumPy performs faster on these arrays.
Example:
arr = np.arange(9).reshape(3,3)
contiguous_arr = np.ascontiguousarray(arr)
NumPy functions are optimized and faster than custom Python code.
Example:
arr = np.array([1,2,3,4,5])
total = np.sum(arr) # Faster than sum([1,2,3,4,5])
Also Read: Top 15 Image Processing Projects Using Python That’ll Wow Recruiters!
Summary:
Following these practices in your python numpy tutorial ensures:
By vectorizing operations, using correct data types, managing copies, and leveraging built-in functions, you can work with NumPy confidently on any dataset.
This python numpy tutorial has introduced you to the core features of NumPy, including arrays, mathematical operations, and array manipulation. Understanding these concepts allows you to process data efficiently and perform complex computations. Following best practices ensures your code is fast, memory-efficient, and reliable. From real-life data analysis to scientific computing and machine learning, mastering numpy in python tutorial techniques prepares you to work with large datasets and solve practical problems confidently.
If you are curious to learn about data science, check out IIIT-B & upGrad’s Executive Diploma in Data Science & AI which is created for working professionals and offers 10+ case studies & projects, practical hands-on workshops, mentorship with industry experts, 1-on-1 with industry mentors, 400+ hours of learning and job assistance with top firms.
Stay informed and inspired with our popular Data Science articles, offering expert insights, trends, and practical tips for aspiring data professionals!
Subscribe to upGrad's Newsletter
Join thousands of learners who receive useful tips
Elevate your career by learning essential Data Science skills such as statistical modeling, big data processing, predictive analytics, and SQL!
SL. No | Top Data Science Skills to Learn | |
1 |
Data Analysis Online Courses | Inferential Statistics Online Courses |
2 |
Hypothesis Testing Online Courses | Logistic Regression Online Courses |
3 |
Linear Regression Courses | Linear Algebra for Analysis Online Courses |
Unlock the power of data with our popular Data Science courses, designed to make you proficient in analytics, machine learning, and big data!
NumPy is a core Python library for numerical computing. It provides fast array structures, mathematical functions, and tools for handling large datasets efficiently. Learning NumPy is essential for data analysis, scientific computing, and machine learning tasks. This is the first step in any python numpy tutorial.
NumPy simplifies numerical computations by offering arrays, vectorized operations, and built-in mathematical functions. Compared to Python lists, it is faster and memory-efficient. Mastering NumPy is important for data analysis, ML, and scientific tasks, making it a must in any numpy in python tutorial.
You can install NumPy using pip: pip install numpy. For Anaconda users, NumPy comes pre-installed, or you can use conda install numpy. Always verify installation with import numpy as np and np.__version__ to ensure you’re ready for your numpy tutorial in python.
NumPy arrays, or ndarray, are multidimensional arrays used for storing numerical data. They support 1D, 2D, and 3D structures and allow fast computation. Arrays are the core of any python numpy tutorial and are more efficient than Python lists for large datasets.
You can create arrays using np.array(), np.zeros(), np.ones(), np.arange(), and np.linspace(). Each method serves different purposes, such as creating sequences, zeros, ones, or evenly spaced values. These techniques are fundamental in every numpy in python tutorial.
Access elements using indexing and slicing. For 1D arrays, use arr[0] or arr[1:3]. For 2D arrays, use arr[row, column]. Efficient indexing is a key topic in any numpy tutorial in python, helping you manipulate and retrieve data accurately.
NumPy supports element-wise operations like addition, subtraction, multiplication, and division. You can also use statistical functions like np.sum() and np.mean(). Learning these operations is essential in any python numpy tutorial for fast and efficient computation.
Ufuncs are vectorized functions that apply operations element-wise. Examples include np.sqrt(), np.exp(), np.sin(), and np.log(). They enhance performance and simplify code, making them a key concept in a numpy in python tutorial.
Reshaping changes an array’s dimensions without modifying its data. Use arr.reshape() for a new shape or arr.flatten() to convert multi-dimensional arrays to 1D. Understanding reshaping is crucial in any numpy tutorial in python for data preparation.
You can join arrays with np.concatenate(), np.vstack(), or np.hstack(). Split arrays using np.split(). These methods are essential for preprocessing datasets and are covered in all python numpy tutorial guides.
A view shares memory with the original array, so changes affect both. A copy creates an independent array. Knowing this distinction prevents errors in your code and is an important topic in any numpy in python tutorial.
NumPy arrays have a dtype to specify data type. Use arr.astype() to convert types, like int32 or float32. Correct data types ensure memory efficiency and computation accuracy in all numpy tutorial in python exercises.
Yes. NumPy handles datasets for sales analysis, stock prices, and scientific measurements. Its arrays and vectorized operations make computations fast. Practical examples are essential in any python numpy tutorial to understand real-world applications.
NumPy prepares numerical data for ML models. It supports feature extraction, normalization, and batch calculations. Efficient data handling with NumPy is a core part of every numpy in python tutorial for ML workflows.
Images are represented as multi-dimensional arrays. NumPy allows easy manipulation of pixels and channels, making it a key tool in image processing tasks covered in many numpy tutorial in python guides.
Use vectorized operations, select appropriate data types, avoid unnecessary copies, and leverage built-in functions. Following these practices ensures faster, memory-efficient, and readable code, a major focus of any python numpy tutorial.
Check array shapes, dtypes, and indexing. Ensure functions match array dimensions and avoid shape mismatches. Debugging efficiently is crucial for beginners in any numpy in python tutorial.
Yes. NumPy arrays are memory-efficient, support vectorized computations, and can be combined with memory-mapped arrays (np.memmap) for huge datasets. Performance tips are covered in advanced sections of numpy tutorial in python.
NumPy works seamlessly with pandas, Matplotlib, SciPy, and scikit-learn. Arrays can be converted to DataFrames or plotted easily, making it essential knowledge in any python numpy tutorial.
After mastering NumPy, practice with real datasets, explore pandas for data manipulation, and apply your skills to machine learning projects. This step ensures practical understanding, completing any numpy in python tutorial journey.
834 articles published
Rohit Sharma is the Head of Revenue & Programs (International), with over 8 years of experience in business analytics, EdTech, and program management. He holds an M.Tech from IIT Delhi and specializes...
Speak with Data Science Expert
By submitting, I accept the T&C and
Privacy Policy
Start Your Career in Data Science Today
Top Resources