Python from import Statement

The from import statement in Python allows you to load a specific function from an external library (module) into memory.

Syntax

from libraryname import functionname

This command imports only the specified function(s) into memory, leaving the rest of the library untouched.

You can use it both in a script and in the interactive Python console.

A Practical Example

In this script, I import the sqrt() function for square roots from the math library.

  1. from math import sqrt
  2. x = 25
  3. print(sqrt(x))

Then, I use the sqrt() function to calculate the square root of 25.

The output is

5.0

The script calculated and printed the square root value.

And that's it!

Note: When you import a function using from import, you should use it without prefixing it with the library name. In other words, you write sqrt() instead of math.sqrt(x).

The Difference Between from import and import

Both statements import external functions from a library into a Python program, but there is an important difference.

  • import loads all the functions from an external library
  • from import loads only the specified functions from the external library.

Therefore, using from import is faster and uses less memory.

 

 
 

Please feel free to point out any errors or typos, or share suggestions to improve these notes. English isn't my first language, so if you notice any mistakes, let me know, and I'll be sure to fix them.

FacebookTwitterLinkedinLinkedin
knowledge base

Python Modules