When should I use np.array([1,2,3]) vs np.array([[1,2,3]]) vs [1,2,3] vs [[1,2,3]]? I know that using an np.array allows you to do certain operations on the array that the list implementation doesn’t, and that using [[]] rather than [] allows you to take transposes, but what’s the general reason for using one over the others?
1 Answer
It is a matter of numpy vs lists and 1d vs 2d dimensions:
np.array([1,2,3])is a 1-dimensional ndarray of 3 elements :type(np.array([1,2,3]))returns<class 'numpy.ndarray'>andnp.array([1,2,3]).shapereturns(3,)np.array([[1,2,3]])is a 2-dimensional ndarray with 1 line and 3 columns :typereturns<class 'numpy.ndarray'>andshapereturns(1,3)[1,2,3]is a 1-dimensional list with 3 elements :type([1,2,3])returns<class 'list'>andlen([1,2,3])returns3[[1,2,3]]is a 2-dimensional list with 1 line and 3 colums :typereturns<class 'list'>,lenreturns1andlen([[1,2,3]][0])returns3. Note that[[1,2,3]][0] = [1,2,3], so the first element of this 2d list is a 1d list.
You must have noted that there is no shape attribute for lists. Lists are basic python objects, and though they have many purposes sometimes you will need to use ndarray, especially is you need to use specific numpy functions. Yet do not change all your lists for ndarray as some operations are way more handy with lists. In all, use ndarray when necessary, and list otherwise.
As for the dimensions, it depends on what you need, but if you do not need a 2-dimensional stuff just go ahead with the 1-dimensional.
[1,2,3]and[[1,2,3]]are not arrays, they are listsnp.arraymakes an array from a list..tolist()does the reverse.reshapeis one way of changing dimensions of an array. Also learn the respective methods. Lists have a limited, but very useful set of methods. Arrays never replace lists (and/or tuples).