How to Import Libraries in Python

In Python, libraries are additional code you can incorporate into your projects, providing pre-written functionality for a wide variety of tasks. Libraries allow you to leverage the work of others so that you don’t have to write everything from scratch. In this tutorial, you will understand how to import a library in Python.

How To Import A Library In Python

In Python, to use any library in your code, you first need to import it. Importing libraries is simple. You just need to use the import keyword followed by the name of the library.

The general syntax to import a library is:

This will import the entire library and all of its functions. If the library is large, importing it all can consume a significant amount of memory and slow down your script. When you don’t need to use all the functions in a library, an alternative is to only import the specific functions you need. Here is how to do this:

Importing Libraries With Aliases

Aliases provide a way of shortening a library’s name to make it easier to use throughout your code. To import a library with an alias, use the as keyword.

This is mostly done with libraries that have complex names. A popular example is the NumPy library, which is often imported under the alias np:

Example

In the following Python code example, we shall import the math library, use a function in it and also import another function from a different library.

The Full Python Code

Output

4.0
2022-09-30 10:02:07.398379

Conclusion

Importing libraries in Python is a simple process, but one that adds a vast amount of functionality to your Python projects. Whether you’re importing an entire library or just specific functions, or using aliases to make your code cleaner, understanding how to import libraries is a key skill in Python programming. Remember, when it comes to libraries, you’re standing on the shoulders of giants!