Reputation: 3572
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?
Upvotes: 36
Views: 10451
Reputation: 362766
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.
Upvotes: 12
Reputation:
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]
Upvotes: 51