Array indexing and slicing are fundamental operations in Python, especially when working with numerical data using libraries like NumPy. These operations allow you to retrieve, modify, or analyze subsets of array data efficiently. Mastering these techniques is critical for effective data manipulation, performance optimization, and clean code design.
This tutorial will explore the theory, syntax, and various practical use cases of array indexing and slicing in Python, focusing mainly on NumPy arrays.
Indexing refers to accessing individual elements of an array using their positional indices. Python uses 0-based indexing, which means the first element is at position 0.
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
print(arr[0]) # 10
print(arr[4]) # 50
Python allows negative indexing to access elements from the end of an array.
print(arr[-1]) # 50
print(arr[-2]) # 40
The syntax for slicing is: array[start:stop:step]
arr = np.array([0, 1, 2, 3, 4, 5, 6])
print(arr[1:5]) # [1 2 3 4]
print(arr[:4]) # [0 1 2 3]
print(arr[3:]) # [3 4 5 6]
print(arr[::2]) # [0 2 4 6]
print(arr[::-1]) # [6 5 4 3 2 1 0]
The third value in the slice is the step. It determines the stride between elements.
print(arr[1:6:2]) # [1 3 5]
print(arr[::3]) # [0 3 6]
matrix = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])
print(matrix[0, 0]) # 1
print(matrix[1, 2]) # 6
print(matrix[0][1]) # 2 (less preferred than matrix[0, 1])
print(matrix[-1, -1]) # 9
# First two rows
print(matrix[:2, :])
# Last two columns
print(matrix[:, 1:])
# Middle element (as 2D slice)
print(matrix[1:2, 1:2])
# Even-indexed rows and columns
print(matrix[::2, ::2])
# Reverse the matrix
print(matrix[::-1, ::-1])
arr = np.array([1, 2, 3, 4, 5, 6])
mask = arr > 3
print(arr[mask]) # [4 5 6]
print(arr[(arr > 2) & (arr < 5)]) # [3 4]
arr[arr % 2 == 0] = 0
print(arr) # [1 0 3 0 5 0]
arr = np.array([10, 20, 30, 40, 50])
indices = [1, 3, 4]
print(arr[indices]) # [20 40 50]
matrix = np.array([
[1, 2],
[3, 4],
[5, 6]
])
rows = [0, 2]
cols = [1, 0]
print(matrix[rows, cols]) # [2 5]
Ellipsis (...) is used to slice arrays with many dimensions more concisely.
arr = np.random.rand(3, 4, 5)
# Access entire third dimension
print(arr[..., 0].shape) # (3, 4)
arr = np.array([1, 2, 3, 4, 5])
arr[1:4] = 0
print(arr) # [1 0 0 0 5]
matrix = np.ones((3, 3))
matrix[:, 1] = [9, 8, 7]
print(matrix)
a = np.array([10, 20, 30])
b = a[1:3]
b[0] = 99
print(a) # [10 99 30]
a = np.array([10, 20, 30])
b = a[1:3].copy()
b[0] = 99
print(a) # [10 20 30]
arr = np.array([5, 10, 15, 20, 25])
indices = np.where(arr > 15)
print(indices) # (array([3, 4]),)
print(arr[indices]) # [20 25]
arr = np.array([1, 2, 3, 4, 5])
new_arr = np.where(arr % 2 == 0, 0, arr)
print(new_arr) # [1 0 3 0 5]
Quick cheatsheet:
matrix = np.array([
[10, 20, 30],
[40, 50, 60],
[70, 80, 90]
])
rows = np.array([True, False, True])
cols = [0, 2]
print(matrix[rows][:, cols])
arr = np.arange(10)
arr[arr % 2 == 0] = -1
print(arr) # [-1 1 -1 3 -1 5 -1 7 -1 9]
Indexing and slicing are foundational tools for working with arrays in Python, especially using NumPy. They enable efficient access and manipulation of data subsets without resorting to slower and more verbose methods like loops. Whether you're filtering rows, reshaping data, or performing conditional replacements, mastering these techniques is essential for any data scientist, engineer, or analyst working with numerical data.
Advanced indexing patterns, including Boolean arrays, fancy indexing, and slicing across multiple dimensions, provide unparalleled flexibility. Understanding how views work, avoiding unintended data modification, and leveraging broadcasted assignments further enhances your ability to write clean and performant code.
With a solid grasp of indexing and slicing, you'll be better prepared to manipulate real-world data efficiently, whether for statistical analysis, machine learning, or scientific computing.
Python is commonly used for developing websites and software, task automation, data analysis, and data visualisation. Since it's relatively easy to learn, Python has been adopted by many non-programmers, such as accountants and scientists, for a variety of everyday tasks, like organising finances.
Learning Curve: Python is generally considered easier to learn for beginners due to its simplicity, while Java is more complex but provides a deeper understanding of how programming works.
The point is that Java is more complicated to learn than Python. It doesn't matter the order. You will have to do some things in Java that you don't in Python. The general programming skills you learn from using either language will transfer to another.
Read on for tips on how to maximize your learning. In general, it takes around two to six months to learn the fundamentals of Python. But you can learn enough to write your first short program in a matter of minutes. Developing mastery of Python's vast array of libraries can take months or years.
6 Top Tips for Learning Python
The following is a step-by-step guide for beginners interested in learning Python using Windows.
Best YouTube Channels to Learn Python
Write your first Python programStart by writing a simple Python program, such as a classic "Hello, World!" script. This process will help you understand the syntax and structure of Python code.
The average salary for Python Developer is βΉ5,55,000 per year in the India. The average additional cash compensation for a Python Developer is within a range from βΉ3,000 - βΉ1,20,000.
Copyrights © 2024 letsupdateskills All rights reserved