PythonSyntax and keywords
import
Loads a module, or selected names from a module, into the current file.
On this page
Example
#Python
import math
from statistics import mean
from collections import Counter as C
print(math.sqrt(144))
print(mean([80, 95, 70]))
print(C("abracadabra").most_common(2))Resultsaved result, you can check it
12.0
81.66666666666667
[('a', 5), ('b', 2)]
Definition and usage
#The import statement loads a module, a file of Python code, and makes its contents available. After import math, you access its elements through the module name: math.sqrt(16).
The notation from math import sqrt imports selected names directly, and import numpy as np gives the module a shorter alias. You can import modules from the standard library, installed packages, and your own files.
Avoid from module import *. This kind of import dumps every name from the module into your file, which makes it hard to tell where a given function came from, and risks overwriting your own variables.
Syntax
#Syntax
import module
from module import name
import module as aliasGood practices
#- Place imports at the top of the file, in this order: standard library, third-party packages, your own modules.
- Use aliases mainly when they are widely accepted, like
import pandas as pd.
Spotted a mistake or missing an example? Write to us.