Writing
NumPy and SciPy: How to Get Started and When You Need Each
Learn NumPy first for fast arrays and vectorised maths, then add SciPy subpackages when you need solvers, statistics or optimisation. Old examples like sp.sqrt no longer run.
By Ka Lun Chan · AI / Learning
Should you learn NumPy or SciPy first?
Learn NumPy first. It gives Python fast arrays and the maths that runs on them, and almost every data science library builds on it. Reach for SciPy when you need an algorithm NumPy doesn’t have, such as optimisation, statistical tests or fuller linear algebra, and import just the subpackage you need.
I first wrote this as two short posts on my old blog. This version merges them, keeps the advice that held up and corrects the code examples, some of which no longer run.
Python covers a lot of ground, from web development (I compared two of its frameworks in Django vs Rails) to data science, machine learning and academic research. The data side is where NumPy matters most.
Why use NumPy instead of plain Python lists?
Because NumPy arrays hold values of one type in a compact block, and its operations run in precompiled C rather than a Python loop. You write one expression for the whole array and it runs far faster than iterating element by element.
NumPy stands for Numerical Python, and it’s the foundation for scientific computing in the language. You import it like any other module. Its docs call the key idea vectorisation: the looping still happens, but behind the scenes in optimised, precompiled code, so c = a * b multiplies two arrays element by element at close to C speed.
Broadcasting is the companion idea. When two arrays have different but compatible shapes, NumPy stretches the smaller one to fit, so adding a row to every row of a grid needs no loop at all. Lists are still fine for a handful of mixed values. Arrays win when you have lots of numbers of the same type.
prices = np.array([19.99, 5.49, 3.75])
quantities = np.array([2, 10, 4])
# Plain Python: a loop, one element at a time
totals = [p * q for p, q in zip(prices, quantities)]
# NumPy: one expression, the loop runs in precompiled code
totals = prices * quantities
# Broadcasting: a smaller array is stretched to fit a larger one
grid = np.arange(6).reshape(2, 3) # [[0, 1, 2], [3, 4, 5]]
grid + np.array([10, 20, 30]) # [[10, 21, 32], [13, 24, 35]]
# Random numbers: create a Generator instead of calling np.random.rand
rng = np.random.default_rng(seed=42)
rng.integers(0, 10, size=5)
rng.normal(size=3)The random numbers example reflects a change since I first wrote this. The recommended way is now to create a Generator with np.random.default_rng() and call methods on it. Passing a seed makes the results reproducible, and keeping the generator in a variable avoids hidden global state.
What’s the best way to learn NumPy?
Pick a small project that needs it and work through it. The best way I’ve found to learn anything is to use it on something real, and NumPy’s official absolute beginners guide covers the basics you’ll need along the way.
When I first wrote this I pointed to a couple of video courses and a third-party cheat sheet. Today I’d start with NumPy: the absolute basics for beginners, which is maintained alongside the library and stays current with it. Then load a CSV of something you care about and answer a question with it.
import numpy as np
np.arange(1, 10) # array([1, 2, 3, 4, 5, 6, 7, 8, 9]): the stop value is excluded
np.arange(1, 11) # 1 to 10 inclusive
dir(np) # list everything NumPy exposesWatch the stop value. np.arange(1, 10) gives one to nine, because the stop is excluded, the same as Python’s range. My original comment said it created values from one to ten, which was wrong. For non-integer steps, the NumPy docs recommend np.linspace instead, because floating-point round-off can change how many values arange returns.
dir(np) is still a quick way to see what’s available, though the list is long. The docs’ search is usually faster once you know roughly what you want. If you’re learning with an AI assistant, check its NumPy answers against the docs, because older code is still common in what it learned from. I wrote more about that in how to learn faster with AI.
When do you need SciPy as well?
When you need a numerical algorithm rather than array basics. SciPy is built on NumPy and adds optimisation, integration, interpolation, signal processing, statistics and a fuller linear algebra module. Import its subpackages explicitly, for example from scipy import linalg, stats.
SciPy’s own tutorial says scipy.linalg contains everything in numpy.linalg plus more advanced routines, and it is always compiled with BLAS and LAPACK support, which is optional for NumPy. If you’re already doing serious linear algebra, that’s a reason to switch modules.
import numpy as np
from scipy import linalg, stats
a = np.array([[3.0, 1.0], [1.0, 2.0]])
b = np.array([9.0, 8.0])
linalg.solve(a, b) # array([2., 3.])
stats.zscore(np.array([1.0, 2.0, 3.0])) # about [-1.22, 0, 1.22]My original advice was to import only what you need because importing isn’t instant. That still holds as a habit, but the reason has shifted. SciPy now loads subpackages lazily, so import scipy is cheap and a subpackage is only loaded when you first use it. The better argument today is clarity: from scipy import stats tells a reader exactly which part of SciPy the file depends on.
What changed since the original examples?
SciPy removed the NumPy functions it used to re-export, so sp.sqrt and sp.arange now raise AttributeError. NumPy 2 also removed several old aliases and changed how scalars print. Use NumPy for array functions and SciPy only for its subpackages.
The second original post compared sp.sqrt(-1), which returned 1j, with np.sqrt(-1), which returned nan. The difference was real, but SciPy’s top-level function was a copy of NumPy’s complex-aware version. Those copies were deprecated and then removed from SciPy’s main namespace in release 1.12.0. The behaviour still exists in NumPy as np.emath.sqrt (also reachable as numpy.lib.scimath).
import numpy as np
np.sqrt(-1) # nan, with "RuntimeWarning: invalid value encountered in sqrt"
np.emath.sqrt(-1) # 1j
np.sqrt(-1 + 0j) # 1j, because the input is complex
np.min(np.arange(1, 20)) # 1
import scipy as sp
sp.sqrt(-1) # AttributeError on current SciPy: the NumPy aliases were removedThe sp.min error in my original was correct then and still is: SciPy never had it, and np.min is the function to use. NumPy 2 brought a few changes a beginner will hit when copying older code:
- Old aliases are gone: use
np.naninstead ofnp.NaN,np.infinstead ofnp.Infandnp.float64instead ofnp.float_. - Scalars print with their type, so a result shows as
np.float64(3.0)rather than3.0. The value is the same. - NumPy scalars keep their precision in mixed arithmetic, so
np.float32(3) + 3.0stays a float32. - The default integer is 64-bit on 64-bit systems, including Windows.
The migration guide notes that Ruff’s NPY201 rule can fix many of the alias changes automatically.
Which library handles which task?
NumPy handles arrays, element-wise maths, random numbers and basic statistics. SciPy handles the algorithms on top: solvers, optimisers, statistical tests, integration and signal processing.
| Task | NumPy | SciPy |
|---|---|---|
| Create arrays | np.array, np.arange, np.linspace | Use NumPy |
| Element-wise maths | np.sqrt, np.exp, a * b | Use NumPy |
| Square root of a negative | np.emath.sqrt | Use NumPy (sp.sqrt is gone) |
| Random numbers | np.random.default_rng() | scipy.stats for distributions and tests |
| Linear algebra | numpy.linalg (core routines) | scipy.linalg (everything in numpy.linalg and more) |
| Descriptive statistics | np.mean, np.std, np.percentile | scipy.stats.describe, zscore |
| Optimisation and curve fitting | None | scipy.optimize |
| Integration and ODEs | None for ODEs | scipy.integrate |
| Interpolation | np.interp (1-D linear) | scipy.interpolate |
| FFT and signals | np.fft | scipy.fft, scipy.signal |
Is it pointless to import NumPy when you have SciPy? I said maybe, maybe not, depending on your needs. Now the answer is clearer. You always need NumPy, because SciPy no longer gives you its functions.
Which other Python libraries build on NumPy?
Most of the data science stack. These are the ones I listed originally, and they’re all still in wide use.
- SciPy for scientific algorithms, covered above.
- pandas for tabular data with labelled rows and columns.
- Matplotlib for charts and plots.
- scikit-learn for classical machine learning models.
- NLTK for natural language processing.
- statsmodels for statistical models and tests.
- TensorFlow and Keras for deep learning.
If machine learning is where you’re headed, what machine learning is covers the concepts and choosing a machine learning framework compares the options. If you’re still deciding on a language, I compared Python and Go, and NumPy is a large part of why Python wins for data work.
Sources
Checked in November against numpy.org (the absolute beginners guide, what is NumPy, the arange, emath.sqrt and random Generator references, and the NumPy 2.0 migration guide and release notes) and docs.scipy.org (the 1.12.0 release notes, the API import guidelines, the main namespace and the linalg tutorial). The table and recommendations are mine. The code examples use documented behaviour but weren’t run for this version.
- NumPy: the absolute basics for beginners
- NumPy: What is NumPy? (vectorization and broadcasting)
- NumPy reference: numpy.arange
- NumPy reference: numpy.emath.sqrt
- NumPy reference: Random Generator
- NumPy 2.0 migration guide
- NumPy 2.0.0 release notes
- SciPy 1.12.0 release notes (expired deprecations)
- SciPy API: Guidelines for importing functions from SciPy
- SciPy API: Main namespace
- SciPy user guide: Linear algebra (scipy.linalg)
Short answers
Should I learn NumPy or SciPy first?
NumPy first. It provides the arrays and element-wise maths that SciPy and most of the Python data stack build on. Add SciPy when you need an algorithm NumPy lacks, such as optimisation, statistical tests or fuller linear algebra.
Why does scipy.sqrt no longer work?
SciPy used to re-export NumPy functions such as sqrt and arange from its main namespace. They were deprecated and then removed in SciPy 1.12.0, so sp.sqrt now raises AttributeError. Use np.sqrt, or np.emath.sqrt if you want a complex result for negative inputs.
Why does np.sqrt(-1) return nan?
np.sqrt works on real floats by default, so the square root of a negative number is nan and NumPy emits a RuntimeWarning. Use np.emath.sqrt(-1) or pass a complex number, such as np.sqrt(-1 + 0j), to get 1j.
Does importing all of SciPy slow my program down?
Much less than it used to. SciPy now loads subpackages lazily, so import scipy is cheap and each subpackage loads when first used. Importing the subpackage you need, such as from scipy import stats, is still clearer for readers.
Start with one dataset
Install NumPy, load one dataset you care about and answer a single question with arrays instead of loops. Add SciPy the first time you need a solver or a statistical test.