CodeBlanks Logo Icon CodeBlanks

numpy vectorization

Learn vectorization with numpy.

What is numpy vectorization?

numpy processes large numeric arrays in C instead of Python loops. Vectorization applies an operation to all elements of an array at once.

For example np.array([1, 2, 3]) ** 2 squares all elements; no loop needed. This is tens of times faster than a Python for loop. numpy is the standard in scientific computing and data analysis. Vectorization both shortens code and speeds it up. The difference matters with large data.

Array operations

Arithmetic on an np.array applies to all elements. a + 1 adds 1 to each, a * 2 multiplies by two, a ** 2 squares.

Operations work between two arrays too: a + b adds element-wise. Since these run in C they are much faster than a Python for loop. Summary methods like .sum(), .mean(), .max() also run vectorized. The difference matters with large datasets.

Practice Compute squares with numpy

Import the module with import numpy as np. Create an array with a = np.array([1, 2, 3]). Square all elements with b = a ** 2. Print b.

Starter code

main.py
# create an array
# square it and print

Sample solution

main.py
import numpy as np

a = np.array([1, 2, 3])
b = a ** 2
print(b)

Expected output

[1 4 9]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the numpy import

Question
import numpy as ____

a = np.array([1, 2, 3])
Answer
import numpy as np

a = np.array([1, 2, 3])

Explanation: import numpy as np is the standard alias.

2 Match numpy concepts

Term Meaning
np.array Creates an array
** 2 Squares all elements
vectorization Loop-free operation
numpy Numeric computing

3 Why is vectorization faster?

  • It uses Python loops
  • It applies the operation in C to the whole array Correct answer
  • It uses less memory
  • It writes shorter code

Explanation: numpy operations run in C; they apply to the whole array without Python interpreter overhead.

All lessons in Expert