How to Check if NumPy Module Is Installed in Python

Manav Narula Feb 02, 2024
  1. Use the import Command to Check if the NumPy Module Is Installed or Not
  2. Use the Installed Packages List to Check if the NumPy Module Is Installed or Not
How to Check if NumPy Module Is Installed in Python

In this tutorial, we will learn how to check if the numpy is installed on your device or not.

Use the import Command to Check if the NumPy Module Is Installed or Not

This is the most basic method to check if numpy is installed or not. We import the numpy module, and if it raises an exception, then it means that the package is not installed.

We use a try...except block. We put the import numpy command in the try block. An exception is raised if the module is not present. We catch this exception using the except command and print the desired message.

See the code below.

try:
    import numpy

    print("NumPy is installed")
except:
    print("Not Installed")

Output:

NumPy is installed

If we want to avoid importing the numpy module, we can use the help command. It will not return documentation for modules that are not installed.

Use the Installed Packages List to Check if the NumPy Module Is Installed or Not

In this method, we check the list of all the packages installed and verify from there if the numpy module is installed or not.

We can check for the numpy module in the dictionary returned by sys.modules.

For example,

import sys

print("numpy" in sys.modules)

Output:

True

We can use the pip list or pip freeze command to check for packages installed using pip.

Sometimes, packages installed using conda may not be recognized by the pip command, so we can use the conda list command and check from that list.

We can run the above commands in a Python script to generate a list of installed packages and check there.

import subprocess
import sys

reqs = subprocess.check_output([sys.executable, "-m", "pip", "freeze"])
installed_packages = [r.decode().split("==")[0] for r in reqs.split()]

print("numpy" in installed_packages)

Output:

True
Author: Manav Narula
Manav Narula avatar Manav Narula avatar

Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.

LinkedIn