NumPy Simple Arithmetic

🔢 NumPy Simple Arithmetic

NumPy allows you to perform fast, element-wise arithmetic operations on arrays without writing loops.
This is one of the biggest advantages of NumPy over normal Python lists.


1️⃣ Import NumPy

import numpy as np

2️⃣ Create NumPy Arrays

a = np.array([1, 2, 3, 4])
b = np.array([5, 6, 7, 8])

3️⃣ Addition ➕

c = a + b
print(c)

Output

[ 6 8 10 12 ]

📌 Performed element-wise


4️⃣ Subtraction ➖

c = b - a
print(c)

Output

[4 4 4 4]

5️⃣ Multiplication ✖

c = a * b
print(c)

Output

[ 5 12 21 32 ]

📌 This is NOT matrix multiplication (that uses dot() or @)


6️⃣ Division ➗

c = b / a
print(c)

Output

[5. 3. 2.33333333 2. ]

✔ Result is float


7️⃣ Power / Exponentiation 🔺

c = a ** 2
print(c)

Output

[ 1 4 9 16 ]

8️⃣ Arithmetic with a Scalar ⭐

print(a + 10)
print(a * 2)

Output

[11 12 13 14]
[2 4 6 8]

📌 This is called broadcasting


9️⃣ Using NumPy Functions (Recommended) ⭐

np.add(a, b)
np.subtract(b, a)
np.multiply(a, b)
np.divide(b, a)

✔ Cleaner
✔ Interview-friendly


🔟 Arithmetic on 2D Arrays

x = np.array([[1, 2],
[3, 4]])
y = np.array([[5, 6],
[7, 8]])

print(x + y)

Output

[[ 6 8]
[10 12]]


1️⃣1️⃣ Comparison with Python Lists ❌ vs ✅

Python List ❌

[1, 2, 3] + [4, 5, 6]
# [1, 2, 3, 4, 5, 6]

NumPy Array ✅

np.array([1,2,3]) + np.array([4,5,6])
# [5 7 9]

1️⃣2️⃣ Common Mistakes ❌

❌ Different array sizes (shape mismatch)
❌ Expecting list-style behavior
❌ Confusing * with matrix multiplication
❌ Division by zero


📌 Interview Questions & MCQs

Q1. NumPy arithmetic is performed:

A) Row-wise
B) Column-wise
C) Element-wise
D) Random

Answer: C


Q2. What does a * b do in NumPy?

A) Matrix multiplication
B) Element-wise multiplication
C) Error
D) Addition

Answer: B


Q3. Which operator is used for power?

A) ^
B) **
C) pow()
D) exp()

Answer: B


Q4. What is broadcasting?

A) Looping
B) Type casting
C) Scalar expansion
D) Sorting

Answer: C


🔥 Real-Life Use Cases

✔ Data analysis
✔ Machine learning calculations
✔ Scientific computing
✔ Image processing
✔ Financial modeling


✅ Summary

  • NumPy supports fast element-wise arithmetic

  • Operations work on arrays of same shape

  • Scalars are broadcast automatically

  • Much faster than Python lists

  • Core concept for Data Science & ML

You may also like...