1

We can import numpy and use its functions directly as:

from numpy import *

a = arraay([1,2,3]) # and it works well.

Why do some people use the following method?

import numpy as np

a= np.array([1,2,3])
ayhan
  • 64,199
  • 17
  • 170
  • 189
TSobhy
  • 55
  • 1
  • 8

2 Answers2

4

The difference is easy: from numpy import * imports all names from the top-level NumPy module into your current "module" (namespace). import numpy as np will just make that top-level NumPy module available if you use np.xxx.

However there is one reason why you shouldn't use from any_module import *: It may just overwrite existing names. For example NumPy has its own any, max, all and min functions, which will happily shadow the built-in Python any, max, ... functions (a very common "gotcha").

My advise: Avoid from numpy import * even if it seems like less effort than typing np. all the time!

MSeifert
  • 133,177
  • 32
  • 312
  • 322
1

It's a matter of neatness but also consistency: you might have multiple functions with the same name from different modules (for instance there's a function called "random" in Numpy, but also in other packages like SciPy) so it's important to denote which exact function you're using from which exact module. This link has a great explanation and makes the point about code readability as well.

neophlegm
  • 365
  • 1
  • 13