0
0
NumPydata~5 mins

Why vectorized operations matter in NumPy

Choose your learning style9 modes available
Introduction

Vectorized operations let us do math on whole lists of numbers at once. This makes our code faster and easier to read.

When adding or multiplying many numbers in a list or array.
When you want to speed up calculations on large datasets.
When you want to avoid writing slow loops over data.
When working with images or signals where data is in arrays.
When doing math on columns of a spreadsheet or table.
Syntax
NumPy
result = array1 + array2
result = array * 2
result = np.sin(array)

Operations apply to each element automatically.

No need for explicit loops like for to process each item.

Examples
Adds two arrays element-wise without a loop.
NumPy
import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
sum_arr = arr1 + arr2
print(sum_arr)
Multiplies each element by 2 in one step.
NumPy
import numpy as np
arr = np.array([1, 2, 3])
double_arr = arr * 2
print(double_arr)
Applies sine function to each element of the array.
NumPy
import numpy as np
arr = np.array([0, np.pi/2, np.pi])
sin_arr = np.sin(arr)
print(sin_arr)
Sample Program

This program adds two big arrays using vectorized addition. It is very fast and simple.

NumPy
import numpy as np

# Create two large arrays
arr1 = np.arange(1_000_000)
arr2 = np.arange(1_000_000, 2_000_000)

# Vectorized addition
result = arr1 + arr2

# Show first 5 results
print(result[:5])
OutputSuccess
Important Notes

Vectorized code runs much faster than loops in Python.

It uses optimized C code inside numpy for speed.

Always try vectorized operations when working with arrays.

Summary

Vectorized operations apply math to whole arrays at once.

They make code simpler and much faster.

Use numpy vectorized operations for big data calculations.