why an extra comma in the shape of a single index numpy array

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]

Leave a Comment

tech