Tuple consumes first singleton dimension of NumPy array

Viewed 99

Given a NumPy array:

    array = np.random.randn(1,1,2)
    print(array.shape)
    # (1, 1, 2)

calling tuple() on it eats the first dimension:

    tupled_array = tuple(array)
    print(tupled_array[0].shape)
    # (1, 2) <- why?

I am curious about why?

If we wrap the NumPy array with a list:

    tupled_list_array = tuple([array])
    print(tupled_list_array[0].shape)
    # (1, 1, 2)
1 Answers

tuple() extracts elements based on the first dimension. np.random.randn(1,1,2) is a 1x1x2 matrix. tuple() turns it into the following tuple: (1x2 matrix, )

On the other hand, if you use np.random.randn(2,1,1), tuple() turns it into: (1x1 matrix, 1x1 matrix)

Related