Check if NumPy Module Is Installed in Python

  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

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
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.