Academic Block

Python NumPy Arrays & ComputingGet Certified

What Is NumPy?

NumPy, short for Numerical Python, is the foundation of scientific computing in Python. It adds a new kind of container called an array, which stores many numbers of the same type in one compact block of memory. Arrays are much faster and much more memory efficient than ordinary Python lists, and they come with a rich set of tools for math.

Data scientists, engineers, and researchers use NumPy to work with temperatures, prices, test scores, images, and sensor readings. The most important idea is vectorization: instead of writing a loop that handles one number at a time, you write one expression that works on the whole array at once. Libraries such as Pandas, Matplotlib, and scikit-learn, which come later in this course, are all built on top of NumPy. The code runs in your browser, so the first time you click Test My Code on this page, NumPy may need a few extra seconds to load.

  • Import: import numpy as np is the standard way to load the library.
  • ndarray: NumPy’s array type. Every item has the same type, called the dtype.
  • Shape: a tuple that describes the size of each dimension, such as (3, 3) for three rows and three columns.
  • Vectorized math: operators such as +, *, and > work on every element at once.
  • Axis: the direction of an operation in a 2D array. axis=0 goes down the columns and axis=1 goes across the rows.
  • Broadcasting: the rule that lets arrays of different shapes work together.
  • Boolean mask: an array of True and False values used to select items.

Creating Arrays

The most direct way to make an array is to pass a Python list to np.array(). NumPy looks at the items and chooses a type for the whole array. If any item is a decimal number, every item becomes a float. Besides lists, NumPy offers helper functions that build arrays for you, such as np.zeros(), np.ones(), np.arange(), and np.linspace().

Every array has useful attributes. The shape attribute tells you the size of each dimension, ndim tells you how many dimensions there are, size gives the total number of items, and dtype shows the data type. The function np.arange() works like range() and np.linspace() creates a chosen number of evenly spaced values between two endpoints, including both ends.

Try It: Create Arrays of Temperatures and Prices

Click Test My Code to run the program. Then change the numbers and run it again.

What this code does: It creates an array of five daily temperatures and prints its shape, number of dimensions, and size. It then shows the data type of a price array and builds arrays with zeros(), arange(), and linspace().
import numpy as np
temps = np.array([58, 71, 64, 49, 77])
print(temps)
print(temps.shape, temps.ndim, temps.size)
prices = np.array([4.99, 12.5, 7.25])
print(prices.dtype)
print(np.zeros(3))
print(np.arange(0, 10, 3))
print(np.linspace(0, 1, 5))

Vectorized Math: No Loops Needed

The biggest advantage of NumPy is that arithmetic works on whole arrays. Writing prices * 1.08 multiplies every price by 1.08 in a single step, and prices - 1 subtracts one from every price. There is no loop in your code, so the program is shorter, easier to read, and much faster, because NumPy runs the loop in optimized compiled code.

Comparison operators are vectorized too. The expression prices > 10 produces an array of True and False values, one for each price. Arrays also have methods such as sum() and mean() that summarize all the values. To keep the printed results easy to read, the examples in this lesson use tolist(), which converts a NumPy array back into a plain Python list.

Try It: Add Sales Tax to Grocery Prices

Click Test My Code. Then change the tax rate and watch every price change at once.

What this code does: It adds 8% sales tax to five grocery prices, subtracts a dollar-off coupon from each price, finds the items that cost more than ten dollars, and calculates the total and the average price.
import numpy as np
prices = np.array([4.50, 12.00, 7.25, 20.00, 3.00])
with_tax = prices * 1.08
print(np.round(with_tax, 2).tolist())
print((prices - 1).tolist())
print((prices > 10).tolist())
print(prices.sum())
print(prices.mean())

Indexing, Slicing, and Boolean Masks

Indexing a NumPy array works just like indexing a list: scores[0] is the first item, and scores[-1] is the last. Slices such as scores[1:4] select a range of items. One important difference is that a slice of an array is a view of the same data, not a copy, so changing the slice also changes the original array. Use .copy() when you need an independent array.

NumPy adds two powerful selection tools. A boolean mask, such as scores[scores >= 70], keeps only the items for which the condition is true. Fancy indexing lets you pass a list of positions, as in scores[[0, 2, 4]], to pick out exactly the items you want. Both create a new array, and both are used constantly when cleaning and analyzing data.

Try It: Select Exam Scores

Click Test My Code. Then change the passing score to 80 and run it again.

What this code does: It reads single items and a slice from an array of six exam scores, keeps only the passing scores with a boolean mask, changes one score, and picks three scores by position.
import numpy as np
scores = np.array([88, 92, 79, 65, 95, 71])
print(scores[0], scores[-1])
print(scores[1:4])
passing = scores[scores >= 70]
print(passing)
scores[3] = 70
print(scores)
print(scores[[0, 2, 4]])

Two-Dimensional Arrays and Axes

NumPy arrays can have more than one dimension. A list of lists becomes a two-dimensional array, like a table with rows and columns. You read one item with two indexes, grades[1, 2], meaning row 1 and column 2, and you can select a whole column with grades[:, 0], where the colon means “every row”.

Functions such as sum(), mean(), max(), and min() accept an axis argument. With axis=0 the function works down each column, which collapses the rows. With axis=1 it works across each row, which collapses the columns. Without an axis, the function uses every item in the array. Remembering which axis collapses which dimension is one of the main skills of NumPy.

Try It: A Gradebook with Three Students

Click Test My Code. Then add a fourth test score to every row and a fourth student.

What this code does: It stores test scores for three students in a table with one row for each student, reads one item and one column, and then calculates column totals, row totals, and the highest score.
import numpy as np
grades = np.array([[88, 92, 79], [65, 70, 85], [95, 90, 100]])
print(grades.shape)
print(grades[1, 2])
print(grades[:, 0])
print(grades.sum(axis=0))
print(grades.sum(axis=1))
print(grades.max())

Reshaping and Broadcasting

The method reshape() rearranges the same data into a different shape without changing the values. The total number of items must stay the same, so six numbers can become two rows of three, or three rows of two, but not four rows of two. The attribute .T gives the transpose, which swaps rows and columns.

Broadcasting is the rule that lets NumPy combine arrays of different shapes. A single number is stretched to match an entire array, as in grid * 10. A one-dimensional array can be stretched across the rows of a two-dimensional array when their sizes match along the last axis, as in grid + offsets. If the shapes cannot be matched, NumPy raises a ValueError instead of guessing.

Try It: Reshape and Broadcast a Grid

Click Test My Code. Then try reshaping the six numbers into three rows of two.

What this code does: It turns six numbers into a grid of two rows and three columns, multiplies the whole grid by a single number, adds a row of offsets to every row of the grid, and transposes the grid.
import numpy as np
numbers = np.arange(1, 7)
grid = numbers.reshape(2, 3)
print(grid)
print(grid * 10)
offsets = np.array([100, 200, 300])
print(grid + offsets)
print(grid.T)

Statistics with NumPy

NumPy includes fast statistical tools, so you can summarize thousands of values in one line. The methods mean(), max(), min(), and std() are available on every array, while np.median(), np.sort(), and np.percentile() are functions you call with the array as an argument. The methods argmax() and argmin() return the position of the largest and smallest values instead of the values themselves.

The standard deviation, std(), measures how spread out the values are around the mean. A small standard deviation means that the values are close together, and a large one means that they are scattered. Combining statistics with boolean masks is a very common pattern, such as selecting every day that was hotter than average.

Try It: A Week of High Temperatures in Phoenix

Click Test My Code. Then change one temperature and see how the statistics change.

What this code does: It calculates the mean, the median, the maximum and its position, and the standard deviation of seven daily high temperatures, selects the days that were above average, and sorts the values.
import numpy as np
highs = np.array([95, 98, 101, 99, 103, 97, 100])
print(highs.mean())
print(np.median(highs))
print(highs.max(), highs.argmax())
print(np.round(highs.std(), 2))
print(highs[highs > highs.mean()])
print(np.sort(highs))

Dot Products and Matrix Multiplication

NumPy is also a linear algebra toolkit. The dot product of two one-dimensional arrays multiplies the items that line up and adds up the results. It is the natural way to calculate a total cost from quantities and unit prices, a weighted average, or the score of a machine learning model. Use np.dot() or the shorter operator @.

It is important to separate two operations that look similar. The operator * multiplies two arrays element by element, which means that the item in each position is multiplied by the item in the same position of the other array. The operator @ performs true matrix multiplication, in which each row of the first matrix is combined with each column of the second. They give different answers, as the example shows.

Try It: Grocery Bill and Matrix Products

Click Test My Code. Then change the quantities and see how the total changes.

What this code does: It uses a dot product to calculate the total cost of apples, milk, and bread from quantities and unit prices, and then compares matrix multiplication with element-by-element multiplication for two small matrices.
import numpy as np
quantities = np.array([3, 2, 4])
unit_prices = np.array([0.5, 3.0, 2.25])
print(np.dot(quantities, unit_prices))
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
print(a @ b)
print(a * b)

Using NumPy with input()

NumPy pairs well with user input. A line typed by the user arrives as text, so you split it, convert each piece to a number, and build an array from the numbers. After that, all of NumPy’s vectorized tools are available: statistics, comparisons, and unit conversions work on the whole data set at once.

In the example below, a list of daily temperatures in degrees Fahrenheit is converted to Celsius with one arithmetic expression, without any loop. Notice that argmax() returns a position counted from zero, so the program adds one to report it as a day number. If the user enters something that is not a number, float() raises a ValueError.

Try It: Convert a Week of Temperatures

The Program Input box is already filled with one line: 68 77 86 95 104. Click Run Code straight away, then try your own temperatures separated by spaces.

What this code does: It reads daily temperatures in Fahrenheit, builds an array, prints the count and the average, reports which day was the hottest, and converts every temperature to Celsius with one expression.
import numpy as np
line = input("Daily temperatures: ")
temps = np.array([float(t) for t in line.split()])
print("Count:", temps.size)
print("Average:", round(temps.mean(), 1))
print("Hottest day:", temps.argmax() + 1)
celsius = (temps - 32) * 5 / 9
print("Celsius:", np.round(celsius, 1).tolist())
Tip: Whenever you are about to write a for loop over the items of an array, stop and ask whether one NumPy expression can do the same job. Vectorized code is shorter and usually many times faster.

Common Mistakes with NumPy

NumPy behaves differently from ordinary Python lists in a few important ways, and those differences cause most beginner errors. The error messages are usually very specific about shapes and types, so read them carefully. When an array operation gives a surprising answer, print the shape and the dtype of each array involved.

  • Using loops instead of vectorized math: a for loop over a large array is slow. Write prices * 1.08 instead.
  • Confusing * and @: * multiplies element by element, while @ performs matrix multiplication. They give different answers.
  • Using and, or, and not with arrays: (a > 1) and (a < 5) raises a ValueError. Use &, |, and ~ with parentheses around each condition: (a > 1) & (a < 5).
  • Forgetting that slices are views: changing a slice changes the original array. Call .copy() for an independent array.
  • Shape mismatches: adding arrays whose shapes cannot be broadcast raises a ValueError. Check .shape on both arrays.
  • Reshaping to the wrong size: np.arange(6).reshape(4, 2) fails because 4 × 2 is not 6.
  • Mixing up the axis: axis=0 works down the columns and axis=1 works across the rows. Test on a small array if you are unsure.
  • Expecting a list’s behavior: [1, 2] + [3] joins two lists, but a NumPy array adds numbers item by item. Use np.append() or np.concatenate() to join arrays.

Good Habits for Working with NumPy

Good NumPy code is short, readable, and free of unnecessary loops. A few habits will help you write that kind of code from the start, and they will also prepare you for Pandas, which builds directly on the ideas in this lesson. Always think of the data as a whole array rather than as a series of separate numbers.

  • Import NumPy as np, exactly like everyone else, so your code is easy for others to read.
  • Prefer vectorized expressions, boolean masks, and built-in methods such as sum() and mean() over loops.
  • Check shape, ndim, and dtype whenever something looks wrong. Most bugs show up there.
  • Use the axis argument deliberately, and test it on a tiny array first.
  • Use .copy() when you want to change an array without affecting the original data.
  • Do not rely on the default integer size of an array. When the exact type matters, state it with dtype=, for example np.array([1, 2, 3], dtype=np.int64).
  • Convert small results with tolist() or round() when you want clean output for printing.

Key Takeaways

NumPy turns Python into a powerful tool for numerical work. Its arrays are compact and fast, and its vectorized operations let you express a calculation on thousands of values in one line. Review the points below before moving on to Pandas, which adds labeled tables of data on top of NumPy arrays.

  • Import NumPy with import numpy as np and create arrays with np.array(), zeros(), arange(), and linspace().
  • An array holds items of one type, and shape, ndim, size, and dtype describe it.
  • Arithmetic and comparison operators work on every item at once, with no loop.
  • Boolean masks and fancy indexing select items, and slices are views of the original data.
  • In two dimensions, axis=0 works down the columns and axis=1 works across the rows.
  • reshape() changes the shape without changing the data, and broadcasting lets arrays of different shapes work together.
  • Use * for element-by-element multiplication and @ or np.dot() for dot products and matrix multiplication.

Frequently Asked Questions

Students new to NumPy often ask why it exists when Python already has lists, and how its operations differ from the ones they know. The answers below summarize the most important points from the examples above. Open a question to read the answer, and run the matching example again if you want to see it in action.

What is NumPy in Python?

NumPy is a library for numerical computing that provides a fast, memory-efficient array type called ndarray, together with functions for math, statistics, linear algebra, and more. It is imported with import numpy as np, and it is the foundation of Pandas, Matplotlib, and scikit-learn.

Why is NumPy faster than Python lists?

A NumPy array stores items of one type in a single block of memory, and its operations run in optimized compiled code instead of in a Python loop. Vectorized expressions such as prices * 1.08 process every item without the overhead of interpreting a loop, which makes them many times faster on large data.

What is the difference between a NumPy array and a Python list?

A list can hold items of different types and is changed with list methods, while a NumPy array holds items of one type and supports vectorized math. Adding two lists joins them, but adding two arrays adds the items in matching positions. Arrays also have a fixed size and a shape.

What are shape and axis in NumPy?

The shape is a tuple that gives the size of each dimension, such as (3, 3) for three rows and three columns. An axis is a dimension along which a function works. For a 2D array, axis=0 works down the columns and axis=1 works across the rows, as in grades.sum(axis=1).

What is broadcasting in NumPy?

Broadcasting is the set of rules that lets NumPy combine arrays of different shapes. A single number is stretched to match a whole array, and a smaller array can be stretched across a larger one when their shapes are compatible, as in grid + offsets. If the shapes cannot be matched, NumPy raises a ValueError.

What is the difference between * and @ for NumPy arrays?

The * operator multiplies two arrays element by element, so items in the same positions are multiplied. The @ operator, like np.dot(), performs matrix multiplication, which combines rows of the first matrix with columns of the second. For two 2 by 2 matrices the two operators give different results.

What is a boolean mask in NumPy?

A boolean mask is an array of True and False values, usually produced by a comparison such as scores >= 70. When you use it as an index, as in scores[scores >= 70], NumPy keeps only the items where the mask is True. To combine conditions, use & and | with parentheses instead of and and or.

Is slicing a NumPy array a copy or a view?

A basic slice such as scores[1:4] is a view of the same data, so changing the slice also changes the original array. Boolean masks and fancy indexing create copies. Call the copy() method when you need an independent array that you can change safely.

Ready for the next step?Work with labeled tables of data using Pandas.
Next: Pandas & Data Analysis →