Python Practice › NumPy Programs › Program 29

Change the sign of a range

EasyNumPy Programs · 29 of 100

Write a NumPy program to create a vector of 1 to 15 and change the sign of the numbers from 6 to 10.

Advertisement
Output
[  1   2   3   4   5  -6  -7  -8  -9 -10  11  12  13  14  15]

Approach

  1. Use a boolean mask and multiply by -1.

Solution

Python
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.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More numpy programs

← All 100 NumPy Programs