NumPy Beginner Practice and Exercises
This lesson provides hands-on exercises for beginners learning NumPy. You will practice creating arrays, accessing elements, slicing arrays, checking attributes, performing arithmetic operations, calculating statistics, applying conditions, and reshaping arrays. Each exercise includes a task, expected output, and solution so that you can practice independently and verify your understanding.
1. Learning Objectives
After completing this practice lesson, you will be able to:
- Create one-dimensional and multidimensional NumPy arrays.
- Use array indexing and slicing.
- Inspect array shape, size, dimensions, and data type.
- Perform arithmetic operations on arrays.
- Calculate sum, mean, minimum, and maximum.
- Filter values using Boolean conditions.
- Reshape arrays and generate sequences.
- Write and test basic NumPy programs independently.
2. Exercise 1: Create a NumPy Array
Task: Create a NumPy array containing the numbers 10, 20, 30, 40, and 50. Display the array and its data type.
Expected Output
The displayed integer data type may differ by platform. NumPy commonly uses
int64 on 64-bit systems for this example, but the exact default
integer type is environment-dependent.
np.array() converts a Python sequence
into a NumPy array.
3. Exercise 2: Create Arrays Using arange()
Task: Generate the integers from 1 through 10 using
np.arange().
Expected Output
The stop value is exclusive. Therefore, np.arange(1, 11) includes 1
through 10 but excludes 11.
4. Exercise 3: Create Zeros and Ones Arrays
Task: Create an array containing four zeros and another array containing five ones.
Expected Output
By default, these functions produce floating-point arrays. Use the
dtype argument if you need integer values.
5. Exercise 4: Access Array Elements
Task: Given an array, display the first element, third element, and last element.
Expected Output
-1 accesses the last element.
6. Exercise 5: Slice an Array
Task: Display the first three elements, the elements from index 1 through index 3, and the last two elements.
Expected Output
In a slice, the starting index is included and the stopping index is excluded.
7. Exercise 6: Check Array Attributes
Task: Create a two-dimensional array and display its shape, number of dimensions, and total number of elements.
Expected Output
| Attribute | Meaning |
|---|---|
shape |
Number of elements along each dimension. |
ndim |
Number of dimensions. |
size |
Total number of elements. |
dtype |
Data type of the array elements. |
8. Exercise 7: Perform Arithmetic Operations
Task: Add, subtract, multiply, and divide two arrays element by element.
Expected Output
NumPy performs these operations element by element when the arrays have compatible shapes.
9. Exercise 8: Calculate Sum and Average
Task: Calculate the sum, mean, minimum, and maximum of a marks array.
Expected Output
10. Exercise 9: Filter Values Using Conditions
Task: Select all values greater than 50 from the array.
Expected Output
The condition numbers > 50 creates a Boolean array. Boolean indexing
returns the values where the condition is True.
11. Exercise 10: Use Multiple Conditions
Task: Select values that are greater than or equal to 30 and less than or equal to 70.
Expected Output
& or |. Use these operators
instead of Python's and and or for element-wise array
conditions.
12. Exercise 11: Reshape an Array
Task: Create an array of 12 integers and reshape it into three rows and four columns.
Expected Output
The total number of elements must remain unchanged. Here, 12 elements are reshaped into a matrix with 3 rows and 4 columns.
13. Exercise 12: Calculate Row and Column Totals
Task: Calculate the sum of each row and each column in a matrix.
Expected Output
axis=1 calculates one result for each row. axis=0
calculates one result for each column.
14. Exercise 13: Generate Evenly Spaced Values
Task: Generate five evenly spaced values between 0 and 10, including both endpoints.
Expected Output
Unlike np.arange(), which uses a step size, np.linspace()
lets you specify the number of values to generate.
15. Exercise 14: Find Unique Values
Task: Find the unique values in an array that contains duplicates.
Expected Output
np.unique() returns the distinct values in sorted order for this
one-dimensional numeric array.
16. Exercise 15: Replace Values Using np.where()
Task: Replace marks greater than or equal to 40 with
"Pass" and all other marks with "Fail".
Expected Output
np.where() selects values according to a condition. It is useful for
applying simple classifications to numerical arrays.
17. Mini Project: Student Marks Analysis
Combine your knowledge of arrays, aggregation, and conditions to analyze marks for three students.
Project Requirements
- Store student names and marks in arrays.
- Calculate each student's average marks.
- Find the highest average.
- Identify students with averages of at least 75.
- Display the final results.
Solution
Expected Output
This mini project demonstrates how NumPy can calculate averages and filter students without requiring a separate calculation for each student.
18. Common Beginner Mistakes
Mistake 1: Incorrect indexing
An array with five elements uses indices 0 through 4. Accessing index 5 raises
an IndexError.
Mistake 2: Forgetting the exclusive stop index
A slice such as numbers[1:4] includes indices 1, 2, and 3, but not 4.
Mistake 3: Reshaping into an incompatible shape
A 12-element array cannot be reshaped into a shape that requires 10 elements. The total element count must match.
Mistake 4: Using and instead of &
For element-wise comparisons across NumPy arrays, use & or
| with parentheses around the individual conditions.
Mistake 5: Confusing axis values
For a two-dimensional array, axis=0 produces column-wise
results and axis=1 produces row-wise results.
19. Beginner Self-Assessment
Try answering these questions without looking at the solutions above. You can use the answers to identify topics that need more practice.
Question 1
Which function creates a NumPy array from a Python list?
A. np.array()
B. np.reshape()
C. np.mean()
D. np.sort()
Question 2
What does np.sum(numbers) calculate?
A. The smallest element
B. The sum of array elements
C. The array dimensions
D. The data type
Question 3
What does numbers[-1] return?
A. The first element
B. The second element
C. The last element
D. The array length
Question 4
Which attribute gives the total number of array elements?
A. shape
B. ndim
C. size
D. dtype
Question 5
Which function generates evenly spaced values over an interval?
A. np.linspace()
B. np.unique()
C. np.min()
D. np.where()
Answer Key
Summary
In this lesson, you practiced creating arrays, generating sequences, indexing, slicing, inspecting array attributes, performing arithmetic, calculating statistics, filtering values, reshaping arrays, and working with conditions. You also completed a student marks mini project and a beginner self-assessment.
Repeat the exercises without copying the solutions until you can write the programs independently. These fundamentals will prepare you for intermediate NumPy exercises involving multidimensional arrays, broadcasting, sorting, aggregation, and more advanced data-analysis tasks.