Code Explanation:
1. Importing the NumPy Library
import numpy as np
Loads the NumPy library into the program.
The alias np is used so you can type np instead of numpy for every function call.
2. Creating a NumPy Array
arr = np.array([1, 2, 3, 4, 5])
Creates a NumPy array named arr containing integers [1, 2, 3, 4, 5].
NumPy arrays store elements of the same type and support vectorized operations (fast element-wise math).
3. Making a Boolean Mask
mask = arr <= 3
Checks, for each element in arr, if it is less than or equal to 3.
Returns a Boolean array:
[ True, True, True, False, False ]
True means the element satisfies the condition (<= 3).
4. Selecting & Modifying Elements with the Mask
arr[mask] = arr[mask] ** 2
arr[mask] selects only the elements where mask is True: [1, 2, 3].
arr[mask] ** 2 squares each selected element → [1, 4, 9].
Assigns these squared values back into their original positions in arr.
Now arr becomes:
[1, 4, 9, 4, 5]
5. Accessing the Second-to-Last Element
print(arr[-2])
arr[-2] means second from the end (negative indexing starts from the right).
In [1, 4, 9, 4, 5], the second-to-last element is 4.
Prints:
4
Final Output:
4
Download Book - 500 Days Python Coding Challenges with Explanation
.png)

0 Comments:
Post a Comment