There's a simply way way to convert a list of numbers in python to a numpy array.
But the simple functions that I have tried, for instance numpy.average(x)
, would work regardless of whether x
is a simple python list or a numpy array. In which type(s) of cases is it required to convert a list (or an array for that matter) in python to an array in numpy?
Best Answer
The answers that have been given thus far are very good.The simple convenience of having much of the NumPy functionality bound to the array object through its methods is very helpful.Here's something that hasn't been mentioned yet.
One very good reason to convert your lists to arrays before passing them to NumPy functions is that, internally, most NumPy functions try to make arguments that ought to be arrays into NumPy arrays before performing any computation.This means that, when you call a NumPy function on a list of values or a list of lists of values, NumPy first converts the list to an array, then runs the computation, then returns the result.
If you make multiple calls to NumPy functions on the same list, NumPy will be forced to construct a new array and copy the values from your array into it every time you make a call to a built in NumPy function.This causes a lot of unnecessary conversions and will slow down every function call.To convert a list to an array, NumPy must iterate through the list you have given to determine a suitable data type and shape, allocate an empty array to hold the needed values, then iterate over the list again to store the value contained in each Python object in the appropriate entry of the array.
All this extra work can slow things down, and it doesn't make sense to do all the same conversions multiple times if they aren't necessary.
Numpy arrays are more compact than python lists, which uses less memory. Numpy is also not just more efficient but convienient. There are a lot of vector and matrix operations in Numpy. There are also things built into Numpy such as FFT's, convolutions, statistics, histograms, etc. There are also things like speed, where for example if you sum the elements of a Numpy array compared to the elements in a list it will be faster. To answer your question in particular Numpy arrays are very beneficial when working with large multi-dimensional arrays or if you want to do of scientific computing, to name a couple things.