Python Practice › NumPy Programs › Program 29
Change the sign of a range
Write a NumPy program to create a vector of 1 to 15 and change the sign of the numbers from 6 to 10.
Output
[ 1 2 3 4 5 -6 -7 -8 -9 -10 11 12 13 14 15]
Approach
- Use a boolean mask and multiply by -1.
Solution
import numpy as npv = np.arange(1, 16)v[(v >= 6) & (v <= 10)] *= -1print(v)Output
[ 1 2 3 4 5 -6 -7 -8 -9 -10 11 12 13 14 15]
Line by line
Line 3
The mask selects 6 to 10 and *= -1 flips their sign in place.
Learn the concept
New to this topic? Read the lesson, then come back.