12.2: “Vectorized” Arithmetic Operators
Recall our table of Python math operators (Figure 5.1.1). What do those things do if we use them on aggregate, instead of atomic data? The answer is: something super cool and useful.
Operating on an Array and a Single Value
Consider the following code:
Code \(\PageIndex{1}\) (Python):
num_likes_today = np.array([6,61,0,0,14])
num_likes_tomorrow = num_likes_today + 3
print(num_likes_tomorrow)
| [ 9 64 3 3 17 ]
See what happened? “Adding 3” to the array means adding 3 to each element. All in one compact line of code, we can do five – or even five billion – operations. This works for all the other Figure 5.1.1 operators as well.
For somewhat geeky reasons, this sort of thing is called a vectorized operation. All you need to know is that this means fast . And that’s “fast” in two different ways: fast to write the code (since instead of using a loop , which we’ll cover in 14, you just write a single statement with + and = signs), and more importantly, fast to execute. For more geeky reasons, the above code will run lightning fast even if num_likes_today had five hundred million elements instead of just five. As you’ll learn if you ever try it, a Python loop is much slower. 2
Don’t get me wrong: there are times we’ll have to use a loop because we have no choice. But the general rule with Python is: if you can figure out how to perform a calculation without using a loop, always do it!
Operating on Two Arrays
Possibly even cooler, we can even “+” (or “-”, or “*”, or...) two entire arrays together. Example:
Code \(\PageIndex{2}\) (Python):
salaries = np.array([38000, 102000, 55750, 29500, 250000])
raises = np.array([1000, 4000, 2000, 1000, 2000])
salaries = salaries + raises
print(salaries)
This code produces:
| [ 39000 106000 57750 30500 252000]
Can you see why? “Adding” the two arrays together performed addition element-by-element . The result is a new array with 38000+ 1000 as the first element, 102000 + 4000 as the second, etc. This, too, is a lightning-fast, vectorized operation, and it too works with all the other math operators.
Just to re-emphasize one point before we go on. In the example back on p. 77, we assigned the result of the operation to a new variable, num_likes_tomorrow . This means that num_likes_today itself was unchanged by the code. In contrast, in the example we just did, we assigned the result of the operation back into an existing variable ( salaries ). So salaries has itself been updated as a result of that code.