Thuta Learning
IntermediateData & Databasesintermediate

Basic Operations

Relax. We'll talk through this in plain words — no textbook voice.

NumPy arithmetic operations work element-wise. That means it computes each pair of elements at matching positions between two arrays individually. You can easily handle things like discounts, tax, score adjustments, and unit conversions without writing a single Python loop.

python
import numpy as np

price = np.array([1000, 1500, 2000])
tax = np.array([50, 75, 100])

print("Price + tax:", price + tax)
print("Price after 10% discount:", price * 0.9)
print("Price difference from 1500:", price - 1500)

price + tax adds elements at matching positions. price * 0.9 multiplies every price element by 0.9, giving you the value after a 10% discount. When you compute an array against a single scalar number, the scalar gets applied to every element.

You should see
Price + tax: [1050 1575 2100] Price after 10% discount: [ 900. 1350. 1800.] Price difference from 1500: [-500 0 500]

Info

To compute two arrays element-wise, their shapes usually need to match. If the shapes differ, it only works if it satisfies the broadcasting rule.

Easy traps

  • For a Python list, [1, 2, 3] * 2 duplicates the list. For a NumPy array, though, it multiplies every element by 2. Don't mix up this difference.

Exercise

Scalar operations are extremely useful for things like currency conversion, unit conversion, and price updates.

python
import numpy as np

usd_prices = np.array([10, 25, 40])
exchange_rate = 2100
mmk_prices = usd_prices * exchange_rate

print("MMK prices:", mmk_prices)

You'll know it worked when: MMK prices: [21000 52500 84000]

Basic Operations | Thuta Learning