Question about .shape attribute in Python


#1

Hello all,

I have a quick question regarding a quirk in Python's .shape attribute. As I'm sure all of you know, .shape returns a tuple corresponding to the dimensions of an array. If an array, a, has n rows and m columns, a.shape will return (n,m).

However, something funny happens when .shape is used on a 1 x m array. Consider the example arrays below.

a = numpy.array([[1, 2, 3], [4, 5, 6]])

As expected, a.shape yields the tuple [2, 3].

b = numpy.array([1, 2, 3])

Naively, I expected b.shape to return [1, 3], but instead it returns [3,]. Also, when trying to access the number of columns directly via b.shape[1], Python throws "IndexError: tuple index out of range".

Does anyone know why .shape gets weird when dealing with a 1 x m array?

Thanks!