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?
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]).shape
returns(3,)
np.array([[1,2,3]])
is a 2-dimensional ndarray with 1 line and 3 columns :type
returns<class 'numpy.ndarray'>
andshape
returns(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 :type
returns<class 'list'>
,len
returns1
andlen([[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.
-
-
I think, given the question, that vulgarization is here more important than accuracy in the vocabulary – jeannej Sep 17 at 20:10
[1,2,3]
and[[1,2,3]]
are not arrays, they are lists – juanpa.arrivillaga Sep 17 at 20:08np.array
makes an array from a list..tolist()
does the reverse.reshape
is 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). – hpaulj Sep 17 at 22:49