Scalar operations let you add, subtract, multiply, or divide every number in an array by a single number easily. This helps you change all values quickly without writing loops.
Scalar operations on arrays in NumPy
import numpy as np array = np.array([values]) # Add a scalar result = array + scalar # Subtract a scalar result = array - scalar # Multiply by a scalar result = array * scalar # Divide by a scalar result = array / scalar
Scalar means a single number, not a list or array.
Operations apply to every element in the array automatically.
import numpy as np array = np.array([1, 2, 3]) result = array + 5 print(result)
import numpy as np array = np.array([]) result = array * 10 print(result)
import numpy as np array = np.array([10]) result = array - 3 print(result)
import numpy as np array = np.array([2, 4, 6]) result = array / 2 print(result)
This program shows how to add, multiply, and divide all elements in a numpy array by a scalar number. It prints the array before and after each operation.
import numpy as np # Create an array of exam scores exam_scores = np.array([70, 85, 90, 60, 75]) print("Original exam scores:", exam_scores) # Add 5 bonus points to all scores bonus_points = 5 updated_scores = exam_scores + bonus_points print("Scores after adding bonus points:", updated_scores) # Multiply all scores by 1.1 to give a 10% increase increased_scores = updated_scores * 1.1 print("Scores after 10% increase:", increased_scores) # Divide all scores by 2 to find half scores half_scores = increased_scores / 2 print("Half of the increased scores:", half_scores)
Time complexity is O(n) where n is the number of elements, because each element is processed once.
Space complexity is O(n) for the new array created by the operation.
Common mistake: Trying to add a list or array instead of a scalar causes element-wise addition, not scalar operation.
Use scalar operations when you want to apply the same change to every element quickly without loops.
Scalar operations apply a single number operation to every element in an array.
They are simple and fast ways to change all values at once.
Remember: the scalar is a single number, not a list or array.