Vectorized Array Operations
Introduction
Welcome to Vectorized Operations. We’re starting Lesson 1 of 5, where we’ll learn how one arithmetic operator can work across a whole NumPy array. We’ll build from a familiar loop, then use multiplication, addition, subtraction, and division to scale or shift values. By the end, we’ll also be able to predict when an operation returns integers or floats.
Recap the Loop Approach and Why It Gets Old
If we wanted to give every price a ten percent discount using ordinary Python, we could visit each price in a loop and save each changed value. That works, but we have to write instructions to repeat the same calculation. NumPy lets us express the calculation once and apply it to the entire array. First, here is the loop approach for comparison:
The loop takes one price at a time, multiplies it by 0.9, and appends the result to a new list. Printing the list shows the discounted prices:
With NumPy, we can perform that same element-by-element calculation with one operator and no loop.
Scale an Array: Multiplication by a Number
Multiplication scales every value in the array by the number on the right. In this code, prices is a NumPy array created with np.array, and np is the common alias for NumPy. The multiplication returns a new array; it does not replace prices. Here, each price becomes 90% of its original value:
The output shows all four discounted prices:
These are the same values the loop produced; only the display differs, because a NumPy array prints without commas. NumPy applies * 0.9 to each element in order. We wrote one multiplication, and NumPy handled the whole array.
Shift an Array: Addition and Subtraction with a Number
Addition and subtraction shift every element by the same amount. Here, prices + 2 adds two to each price. Replacing + with - shifts each value down by two instead. These expressions also produce new arrays, leaving prices unchanged.
The first line shows addition. The second shows subtraction working in the same way:
Notice that each result keeps the original array’s decimal values. The operation changes the values, not the number of elements.
