0

When calling numpy.array in the following two ways:

>>> np.array((1,2,3,4))
array([1, 2, 3, 4])
>>> np.array([1,2,3,4])
array([1, 2, 3, 4])

I notice it returns two seemingly identical ndarrays. Are both of these ndarrays identical? Why?

3
  • 3
    Yes they read both from an iterable that yields the same numbers. Commented Feb 11, 2020 at 22:49
  • List and tuples don't really differ in the data they carry. They only differ by the features they are supporting. The only feature used in your code is to yield a sequence of items and that is supported by both. Commented Feb 11, 2020 at 22:55
  • When making a basic numpy array like this, they are the same. When using a compound dtype (to make a structured array) they have different meanings. See my recent answer for example: stackoverflow.com/questions/60174899/… Commented Feb 12, 2020 at 0:37

1 Answer 1

2

We can behave in a general way here. Suppose we don't know what X = np.array([1,2,3,4]) and Y = np.array((1,2,3,4)) are. If we print it, we can see an output which is the result of a secret built-in methods X.__repr__ and Y.__repr__. You can see here for sure that both X and Y has the same representations. It doesn't mean, however, that they are the same because they can be instances of different classes with the same representations. To make it sure, I usually use X.__class__ and Y.__class__. So both X and Y are instances of the same class np.ndarray.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.