36

A numpy array a a = numpy.arange(12)

has shape a.shape = (12,)

Why do we need the comma? is shape (12) reserved for something else?

2 Answers 2

51

The reason we don't use (12) for a one-element tuple (like [12] for one-element list) is that round parentheses also appear in formulas. E.g., in x = 2*(5+7) the part (5+7) is just a number, not a tuple. But what if we actually meant it to be a one-element tuple? The trailing comma is a way to indicate that. Compare:

>>> 2*(5+7)
24
>>> 2*(5+7,)
(12, 12)

With lists, the trailing comma is not needed although some style guides recommend it for consistency.

>>> 2*[5+7]
[12, 12]
>>> 2*[5+7,]
[12, 12]
Sign up to request clarification or add additional context in comments.

Comments

12

A numpy array's shape property always returns a tuple.

The number of dimensions and items in an array is defined by its shape, which is a tuple of N positive integers that specify the sizes of each dimension.

(12,) is just a one-element tuple, so this indicates that you have a one-dimensional array (because the tuple has length 1) with a size of 12.

Documented here.

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.