What is the difference between Numpy\'s array() and asarray() functions? When should you use one rather than the other? They seem to generate identical output for all the in
Since other questions are being redirected to this one which ask about asanyarray or other array creation routines, it's probably worth having a brief summary of what each of them does.
The differences are mainly about when to return the input unchanged, as opposed to making a new array as a copy.
array offers a wide variety of options (most of the other functions are thin wrappers around it), including flags to determine when to copy. A full explanation would take just as long as the docs (see Array Creation, but briefly, here are some examples:
Assume a is an ndarray, and m is a matrix, and they both have a dtype of float32:
np.array(a) and np.array(m) will copy both, because that's the default behavior.np.array(a, copy=False) and np.array(m, copy=False) will copy m but not a, because m is not an ndarray.np.array(a, copy=False, subok=True) and np.array(m, copy=False, subok=True) will copy neither, because m is a matrix, which is a subclass of ndarray.np.array(a, dtype=int, copy=False, subok=True) will copy both, because the dtype is not compatible.Most of the other functions are thin wrappers around array that control when copying happens:
ndarray (copy=False).ndarray or subclass like matrix (copy=False, subok=True).ndarray in contiguous C order (copy=False, order='C').ndarray in contiguous Fortran order (copy=False, order='F').object array with the iterator); always copied.There are also convenience functions, like asarray_chkfinite (same copying rules as asarray, but raises ValueError if there are any nan or inf values), and constructors for subclasses like matrix or for special cases like record arrays, and of course the actual ndarray constructor (which lets you create an array directly out of strides over a buffer).