-1

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?

jeannej
  • 1,135
  • 1
  • 9
  • 23
gkeenley
  • 6,088
  • 8
  • 54
  • 129
  • One is 1D and the other is 2D? If you find yourself asking this with no clear understanding of the difference, then you need to stick to 1D. It means there's a very high chance that you really just don't need 2D operations – roganjosh Sep 17 '19 at 19:10
  • @roganjosh, yesterday the OP asked question seeking an outer product of 1d arrays - but trying to use matrix products. – hpaulj Sep 17 '19 at 19:21
  • 1
    you could have just asked "what's the reason to use numpy arrays" - this should get you started : https://numpy.org/devdocs/user/quickstart.html – B.Kocis Sep 17 '19 at 19:39
  • 1
    `[1,2,3]` and `[[1,2,3]]` are not arrays, they are lists – juanpa.arrivillaga Sep 17 '19 at 20:08
  • The best answer depends on what you are trying to do with these objects. Until that is clear, I think you have a lot to learn about how to convert one form into another. `np.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 '19 at 22:49

1 Answers1

0

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'> and np.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'> and shape returns (1,3)
  • [1,2,3] is a 1-dimensional list with 3 elements : type([1,2,3]) returns <class 'list'> and len([1,2,3]) returns 3
  • [[1,2,3]] is a 2-dimensional list with 1 line and 3 colums : type returns <class 'list'>, len returns 1 and len([[1,2,3]][0]) returns 3. 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.

jeannej
  • 1,135
  • 1
  • 9
  • 23