5

There are two options which create arrays:

x = numpy.array([[5, 5, 3, 2], [2, 1, 0, 9], [3, 7, 6, 0]])
y = numpy.array([(5, 5, 3, 2), (2, 1, 0, 9), (3, 7, 6, 0)])

But they have both same outputs.

[[5 5 3 2]
[2 1 0 9]
[3 7 6 0]]

They have both same type:

<class 'numpy.ndarray'>  

Which one is better and what is the difference?

  • 2
    For a numeric array like that they are interchangeable. One's a list of lists the other a list of tuples. When creating a structured array, the list of tuples is required, but that may be a more advanced topic – hpaulj Jun 27 '17 at 22:46

2 Answers2

9

Python has tuples (with round brackets, like (1,4,2,5)) and lists (with square brackets, like [1,4,2,5]). Tuples are immutable ordered collections: once constructed, neither the length nor the elements can change (one can however alter the state of the individual elements given these are mutable). Both are used for different purposes.

But if you construct a 2d numpy array, then both will result in the same array, since numpy will simply read the elements in the list/tuple and copy the data into an array. It is only if for instance the rows have a different length, that numpy will construct an object array, and then it will reference to the tuples/lists.

Tom Auger
  • 19,421
  • 22
  • 81
  • 104
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
2

From numpy's point of view - there is no difference between the two options: the resulting arrays are "identical" in everything.

AGN Gazer
  • 8,025
  • 2
  • 27
  • 45