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

Range and Linspace Arrays

Generate numerical sequences with controlled increments, create evenly spaced values, understand endpoint behavior, and select the right function for your numerical tasks.

1. Learning Objectives

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

  • Explain the purpose of np.arange().
  • Generate sequences using start, stop, and step values.
  • Create evenly spaced values using np.linspace().
  • Control the number of generated values and endpoint inclusion.
  • Generate descending sequences.
  • Understand important differences between the two functions.
  • Apply these functions to practical numerical problems.

2. Introduction to Numerical Sequences

A numerical sequence is an ordered collection of values. In programming, sequences are useful for generating indexes, measurements, time intervals, mathematical inputs, and test data.

NumPy provides two useful functions for generating sequences: np.arange() and np.linspace(). Both create arrays, but they let you control the generated values in different ways.

Example: Generate a Simple Sequence

import numpy as np

numbers = np.arange(1, 6)

print(numbers)

Output:

[1 2 3 4 5]

The generated array contains integers starting at 1 and stopping before 6.

3. Understanding np.arange()

The np.arange() function generates values separated by a specified step size.

General syntax:

np.arange(start, stop, step)
Parameter Description Default Behavior
start The beginning of the sequence. Defaults to 0 if omitted.
stop The boundary where generation stops. Required.
step The increment between values. Defaults to 1.

Example 1: Start and Stop

values = np.arange(2, 8)

print(values)

Output:

[2 3 4 5 6 7]

Example 2: Custom Step Size

values = np.arange(0, 15, 3)

print(values)

Output:

[ 0  3  6  9 12]

Example 3: Odd Numbers

odd_numbers = np.arange(1, 12, 2)

print(odd_numbers)

Output:

[ 1  3  5  7  9 11]
Remember: The stop value is excluded. In np.arange(2, 8), the last value is 7, not 8.

4. Generating Descending Sequences

A negative step allows np.arange() to generate values in descending order. The starting value must be greater than the stop boundary for a typical descending sequence.

Example: Count Backwards

countdown = np.arange(10, 0, -2)

print(countdown)

Output:

[10  8  6  4  2]

Example: Descending Integers

numbers = np.arange(5, -1, -1)

print(numbers)

Output:

[5 4 3 2 1 0]
Common mistake: A negative step is needed for descending ranges. If the step direction does not move from the start toward the stop boundary, the result may be an empty array.

5. Understanding np.linspace()

The np.linspace() function creates a specified number of evenly spaced values between a starting value and an ending value.

General syntax:

np.linspace(start, stop, num=50, endpoint=True)
Parameter Description
start The first value in the interval.
stop The ending boundary.
num The number of values to generate. Defaults to 50.
endpoint Controls whether the stop value is included. Defaults to true.

Example 1: Five Evenly Spaced Values

values = np.linspace(0, 20, num=5)

print(values)

Output:

[ 0.  5. 10. 15. 20.]

Example 2: Four Values Between 2 and 8

values = np.linspace(2, 8, num=4)

print(values)

Output:

[2. 4. 6. 8.]

Example 3: Exclude the Endpoint

values = np.linspace(
    0,
    10,
    num=5,
    endpoint=False
)

print(values)

Output:

[0. 2. 4. 6. 8.]
Tip: Use np.linspace() when you know how many evenly spaced points you need.

6. Visualizing the Difference

np.arange(0, 11, 2) 0 2 4 6 8 10 np.linspace(0, 10, 6) 0 2 4 6 8 10 Both examples produce six evenly spaced values. arange controls the step; linspace controls the number of points.
Figure 1: The two functions can produce similar sequences while using different parameters.

In the examples above, the numerical results are similar. However, np.arange() calculates values from a step size, while np.linspace() calculates values based on the requested number of points.

7. Understanding Step Size in np.linspace()

When the endpoint is included and more than one point is requested, the spacing between adjacent values is:

Spacing formula:

\[ \text{Spacing} = \frac{\text{stop} - \text{start}}{\text{num} - 1} \]

For example, if the start is 0, the stop is 12, and the number of points is 4, the spacing is:

\[ \frac{12 - 0}{4 - 1} = 4 \]

values = np.linspace(0, 12, num=4)

print(values)

Output:

[ 0.  4.  8. 12.]
Special case: When only one point is requested, np.linspace() returns that single point at the start value. Do not use the spacing formula with num=1, because it would divide by zero.

8. Comparing np.arange() and np.linspace()

Feature np.arange() np.linspace()
Main parameters Start, stop, step. Start, stop, number of points.
Stop value Excluded. Included by default.
Control over count Indirect, based on range and step. Directly controlled by num.
Best suited for Integer sequences and regular increments. A fixed number of evenly spaced values.
Floating-point step behavior Floating-point precision can affect generated values. Useful when the number of points is more important than the step.

Example: Compare Different Requirements

import numpy as np

# Generate values at intervals of 5.
step_values = np.arange(0, 21, 5)

# Generate exactly five points between 0 and 20.
point_values = np.linspace(0, 20, num=5)

print("Step-Based:", step_values)
print("Point-Based:", point_values)

Output:

Step-Based: [ 0  5 10 15 20]
Point-Based: [ 0.  5. 10. 15. 20.]

9. Practical Program: Generate Measurement Values

At CIIT TRANING INSTITUTE, Samiksha is preparing a set of measurement points for a numerical exercise. She needs a regular integer sequence and a fixed number of evenly spaced decimal values.

Complete Program

import numpy as np

measurement_steps = np.arange(0, 51, 10)
measurement_points = np.linspace(0, 1, num=6)

print("Measurement Steps:")
print(measurement_steps)

print("Measurement Points:")
print(measurement_points)

print("Number of Steps:", measurement_steps.size)
print("Number of Points:", measurement_points.size)

Output:

Measurement Steps:
[ 0 10 20 30 40 50]

Measurement Points:
[0.  0.2 0.4 0.6 0.8 1. ]

Number of Steps: 6
Number of Points: 6

The first array increases in increments of 10. The second array contains six evenly spaced values from 0 through 1.

10. Common Mistakes and Best Practices

1. Expecting np.arange() to Include Stop

The stop boundary is excluded. Check whether the last value you need is included in the generated sequence.

2. Confusing Step and Number of Points

Use step with np.arange() and num with np.linspace().

3. Using the Wrong Step Direction

A descending sequence usually requires a negative step. An ascending sequence usually requires a positive step.

4. Assuming Floating-Point Values Are Exact

Decimal values may be represented approximately in binary floating-point. Avoid relying on exact equality when comparing computed decimal values.

5. Forgetting Endpoint Settings

The endpoint parameter in np.linspace() defaults to true. Set it to false when the final boundary should be excluded.

11. Classroom Practice Activity

Activity: Generate and Compare Sequences

Samadhan, Pradnya, and Samiksha can complete this activity to practice sequence generation.

  1. Generate integers from 1 through 15 using np.arange().
  2. Generate even numbers from 2 through 30.
  3. Create a descending sequence from 20 to 0 in steps of -5.
  4. Generate exactly five evenly spaced values between 0 and 100.
  5. Generate eight evenly spaced values between -1 and 1.
  6. Generate five values between 0 and 10 with the endpoint excluded.
  7. Display the shape and size of each generated array.

Starter Code

import numpy as np

sequence = np.arange(1, 16)
even_numbers = np.arange(2, 31, 2)
descending = np.arange(20, -1, -5)

five_points = np.linspace(0, 100, num=5)
decimal_points = np.linspace(-1, 1, num=8)
excluded_endpoint = np.linspace(
    0,
    10,
    num=5,
    endpoint=False
)

print("Sequence:", sequence)
print("Even Numbers:", even_numbers)
print("Descending:", descending)
print("Five Points:", five_points)
print("Decimal Points:", decimal_points)
print("Endpoint Excluded:", excluded_endpoint)

print("Sequence Shape:", sequence.shape)
print("Decimal Points Size:", decimal_points.size)

Review Questions

  1. What is the main purpose of np.arange()?
  2. Why is the stop value excluded from an np.arange() result?
  3. What does the step parameter control?
  4. What is the role of num in np.linspace()?
  5. How can you exclude the endpoint in np.linspace()?
  6. How do you create a descending sequence?
  7. When should you prefer np.linspace() over np.arange()?
  8. What spacing is produced by np.linspace(0, 12, num=4)?

Summary

In this lesson, you learned to generate numerical sequences using np.arange() and evenly spaced values using np.linspace().

You explored start, stop, and step parameters, descending sequences, endpoint control, and the difference between controlling a step size and controlling the number of points.