Home > Enterprise >  What is the difference between np.array([val1, val2]) and np.array([[val1, val2]])?
What is the difference between np.array([val1, val2]) and np.array([[val1, val2]])?

Time:07-13

What is the difference between np.array([1, 2]) and np.array([[1, 2]])? Which one of them is a matrix? I also do not understand the output for shape of the above tensors. The former returns (2,) and the latter returns (1,2).

CodePudding user response:

np.array([1, 2]) builds an array starting from a list, thus giving you a 1D array with the shape (2, ) since it only contains a single list of two elements.

When using the double [ you are actually passing a list of lists, thus this gets you a multidimensional array, or matrix, with the shape (1, 2).

With the latter you are able to build more complex matrices like:

np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

rendering a 3x3 matrix:

array([[1, 2, 3],
      [4, 5, 6],
      [7, 8, 9]])
  • Related