-4

When is from and import used? How does the two lines differ? What do they do?

from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt
Austin
  • 25,759
  • 4
  • 25
  • 48
S. Rn
  • 1

3 Answers3

0

The first line imports the specific class ListedColormap from matplotlib.colors package.
The second line gives an alias plt to the package matplotlib.pyplot so that you can call any function or class of the package as plt.func()

Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
0

import module

This imports the entire module. In this instance to access any functions defined in the module you would need to use "module.function"

from module import part_of_module

This imports a part of a module e.g. a class or function.

If you add the alias e.g.

import pandas as pd

Then you can access pandas functions etc. using e.g. pd.DataFrame rather than pandas.DataFrame, for brevity/convenience to call it what you want.

It is also an option, but not recommended, to go

from module import *

This imports the entire module, but if you want to use a function from that module you no longer need to explicitly state module.function in order to use it. This is not recommended because you could have multiple functions with the same name which could result in calling the wrong function.

-1
from matplotlib.colors import ListedColormap

Import a specific class from a package.

import matplotlib.pyplot as plt

Import the package as an aliased package name.

solidpixel
  • 10,688
  • 1
  • 20
  • 33