Master NumPy From Scratch

Learn NumPy fundamentals, arrays, indexing, slicing, data types, array operations, broadcasting, mathematical functions, statistics, random numbers, linear algebra, file handling, and practical projects through structured lessons.

COURSE SYLLABUS
1. NumPy Introduction and Installation
Introduction to NumPy NumPy Installation and Setup NumPy Environment and IDE Setup First NumPy Program
2. NumPy Arrays and Array Creation
NumPy Array Fundamentals Array Creation Functions Zeros, Ones and Identity Arrays Range and Linspace Arrays
3. NumPy Array Indexing and Slicing
One-Dimensional Array Indexing Array Slicing Techniques Two-Dimensional Array Indexing Boolean and Fancy Indexing
4. NumPy Data Types and Attributes
NumPy Data Types Array Shape, Size and Dimensions Data Type Conversion and Casting Array Inspection and Attributes
5. NumPy Array Shape and Reshaping
Reshape and Flatten Arrays Transpose and Axis Operations Stacking and Splitting Arrays Expand and Squeeze Dimensions
6. NumPy Array Operations and Broadcasting
Arithmetic Array Operations Comparison and Logical Operations Broadcasting Fundamentals Universal Functions and Vectorization
7. NumPy Mathematical and Statistical Functions
Mathematical Functions Aggregate and Statistical Functions Minimum, Maximum and Percentiles Rounding and Trigonometric Functions
8. NumPy Filtering and Sorting
Array Filtering and Conditions Sorting and Searching Arrays Unique Values and Set Operations Where, Select and Nonzero Functions
9. NumPy Copies and Views
Array Copies and Views Shallow and Deep Copy Concepts Memory Layout and Contiguity Array Iteration and Memory Efficiency
10. NumPy Random Number Generation
Random Generator Fundamentals Random Integers and Sampling Probability Distributions Random Seeds and Simulation
11. NumPy Linear Algebra
Vectors and Matrices Matrix Multiplication and Dot Product Determinants and Matrix Inverse Eigenvalues and Linear Equations
12. NumPy File Input and Output
Importing and Exporting Text Files CSV Data with NumPy Binary Files and NPY Format NPZ Files and Data Persistence
13. NumPy Practical Projects
Student Marks Analysis Project Sales Data Analysis Project Random Simulation Project Image Array Processing Project
14. NumPy Practice and Assessment
NumPy Beginner Practice NumPy Intermediate Exercises NumPy Advanced Challenges Final NumPy Assessment

One-Dimensional Array Indexing

Learn how to access individual elements in a NumPy array, use positive and negative indexes, update values, and retrieve data safely in numerical programs.

1. Learning Objectives

By the end of this lesson, you will be able to:

  • Explain how indexing works in a one-dimensional array.
  • Access elements using positive indexes.
  • Access elements using negative indexes.
  • Update individual array elements.
  • Retrieve first and last elements.
  • Use loops to access array values.
  • Recognize and prevent common indexing errors.

2. What Is Array Indexing?

Array indexing is the process of accessing an individual element by specifying its position in an array. NumPy uses zero-based indexing, meaning that the first element has index 0.

Example: Create an Array

import numpy as np

numbers = np.array([10, 20, 30, 40, 50])

print(numbers)

Output:

[10 20 30 40 50]

Each element has a position, called its index. We can use that index to access the required value without displaying the entire array.

3. Understanding Positive Indexing

Positive indexing begins at zero and increases from left to right. For an array with five elements, the valid positive indexes are 0, 1, 2, 3, and 4.

10 20 30 40 50 Index 0 Index 1 Index 2 Index 3 Index 4 numbers[2] returns 30
Figure 1: Positive indexes identify each element's position.

Accessing Individual Elements

import numpy as np

numbers = np.array([10, 20, 30, 40, 50])

print(numbers[0])
print(numbers[1])
print(numbers[2])
print(numbers[4])

Output:

10
20
30
50
Remember: The first element is at index 0, not index 1. An array containing five elements has a last positive index of 4.

4. Understanding Negative Indexing

Negative indexing accesses elements by counting from the end of the array. The index -1 refers to the last element, -2 refers to the second-last element, and so on.

10 20 30 40 50 Index -5 Index -4 Index -3 Index -2 Index -1 numbers[-1] returns 50
Figure 2: Negative indexes count backward from the final element.

Example: Access Values from the End

import numpy as np

numbers = np.array([10, 20, 30, 40, 50])

print(numbers[-1])
print(numbers[-2])
print(numbers[-3])

Output:

50
40
30
Positive Index Negative Index Element
0 -5 10
1 -4 20
2 -3 30
3 -2 40
4 -1 50

5. Updating Array Elements

You can change an element by assigning a new value to a valid index. This modifies the original array.

Example: Update a Value

import numpy as np

numbers = np.array([10, 20, 30, 40, 50])

numbers[2] = 99

print(numbers)

Output:

[10 20 99 40 50]

The element at index 2 was changed from 30 to 99. The other elements remain unchanged.

Updating the Last Element

numbers[-1] = 100

print(numbers)

Output:

[ 10  20  99  40 100]
Important: NumPy arrays have a defined data type. Assigning a value of a different type may convert it to the array's existing type. For example, assigning a decimal value to an integer array may discard its fractional part.

6. Finding the First and Last Elements

The first and last elements are frequently needed in data analysis. You can access them directly with index 0 and index -1.

Example: Student Marks

import numpy as np

marks = np.array([76, 89, 94, 68, 83])

first_mark = marks[0]
last_mark = marks[-1]

print("First Mark:", first_mark)
print("Last Mark:", last_mark)

Output:

First Mark: 76
Last Mark: 83

Samadhan can use these expressions to retrieve the first and last marks from a recorded sequence without searching through every element.

7. Accessing Array Elements with Loops

A loop can process array elements one at a time. You can either iterate directly over the values or use indexes when each element's position is also needed.

Example 1: Iterate Directly over Values

import numpy as np

numbers = np.array([10, 20, 30])

for value in numbers:
    print(value)

Output:

10
20
30

Example 2: Iterate Using Indexes

numbers = np.array([10, 20, 30])

for index in range(len(numbers)):
    print("Index:", index, "Value:", numbers[index])

Output:

Index: 0 Value: 10
Index: 1 Value: 20
Index: 2 Value: 30
Best practice: If you only need the values, iterate directly over the array. If you need the position as well, use indexes or Python's enumerate() where appropriate.

8. Checking Array Length and Valid Indexes

The len() function returns the number of elements along the first axis of a one-dimensional array. The size attribute gives the total number of elements.

Example: Inspect the Array

import numpy as np

numbers = np.array([5, 10, 15, 20])

print("Length:", len(numbers))
print("Size:", numbers.size)
print("Last Valid Index:", len(numbers) - 1)

Output:

Length: 4
Size: 4
Last Valid Index: 3

If the array contains four elements, its positive indexes range from 0 to 3. Accessing index 4 raises an IndexError.

Safety check: Before accessing an element using a variable index, verify that the index falls within the valid range.

9. Practical Program: Student Marks Lookup

At CIIT TRANING INSTITUTE, Pradnya is working with a sequence of marks. She wants to retrieve selected values, update one mark, and display the final array.

Complete Program

import numpy as np

marks = np.array([76, 89, 94, 68, 83])

print("Original Marks:", marks)
print("First Mark:", marks[0])
print("Third Mark:", marks[2])
print("Last Mark:", marks[-1])

marks[1] = 91

print("Updated Marks:", marks)
print("Number of Marks:", len(marks))

Output:

Original Marks: [76 89 94 68 83]
First Mark: 76
Third Mark: 94
Last Mark: 83
Updated Marks: [76 91 94 68 83]
Number of Marks: 5

The program uses positive and negative indexes to retrieve elements, updates one value, and checks the number of elements in the array.

10. Common Mistakes and Best Practices

1. Starting the Index at One

Python and NumPy use zero-based indexing. The first element is accessed with index 0.

2. Using an Out-of-Range Index

For an array with five elements, index 5 is invalid. The last valid positive index is 4.

3. Confusing Negative Indexes

Index -1 is the last element, while index -2 is the second-last element.

4. Updating the Wrong Element

Check the index-to-element mapping before assigning a new value.

5. Forgetting Data Type Conversion

Values assigned to an array may be converted to its existing data type.

11. Classroom Practice Activity

Activity: Index and Update an Array

Samadhan, Pradnya, and Samiksha can complete these exercises to practice one-dimensional indexing.

  1. Create an array containing 12, 24, 36, 48, and 60.
  2. Print the first, third, and last elements.
  3. Print the second-last element using negative indexing.
  4. Change the element at index 1 to 25.
  5. Change the last element to 65.
  6. Print every element using a loop.
  7. Display the array length and its last valid positive index.

Starter Code

import numpy as np

numbers = np.array([12, 24, 36, 48, 60])

print("First:", numbers[0])
print("Third:", numbers[2])
print("Last:", numbers[-1])
print("Second Last:", numbers[-2])

numbers[1] = 25
numbers[-1] = 65

print("Updated Array:", numbers)

for value in numbers:
    print(value)

print("Length:", len(numbers))
print("Last Valid Index:", len(numbers) - 1)

Review Questions

  1. What is array indexing?
  2. Why does the first element have index 0?
  3. What does the index -1 represent?
  4. How can you update an element in a NumPy array?
  5. How do you access the second-last element?
  6. What is the difference between iterating over values and iterating over indexes?
  7. What happens when you access an invalid index?
  8. How can you find the last valid positive index of a non-empty one-dimensional array?

Summary

In this lesson, you learned to access one-dimensional NumPy array elements using positive and negative indexes. You also practiced updating individual elements and retrieving the first and last values.

You explored loops, array length, valid index ranges, and common indexing errors through practical examples.