2

My preferred method of manually defining a numpy array is to input in a list of tuples after seeing it done so in the numpy's user guide. It makes tracking the brackets a little easier:

Numpy User Guide

But further searching through the documentation I don't know if this is considered the standard, or if there is a specific use case to it. On the whole, they seem to work exactly the same way as inputting in a list of lists except when trying to explicitly define a 2D array. It automatically becomes a 1D array while a list of lists using the same syntax becomes a 2D array.

In the code below, I would expect a2 to have the same shape as b1. Is there a reason for them being different?

a1 = np.array([1, 1])
print(a1.shape) # (2,)

a2 = np.array([[1], [1]])
print(a2.shape) # (2, 1)

b1 = np.array([(1), (1)])
print(b1.shape) # (2,)

b2 = np.array(((1, 2), (1, -5)))
print(b2.shape) # (2, 2)

Al-Baraa El-Hag
  • 770
  • 6
  • 15

1 Answers1

4

In python, a one-element tuple actually requires a comma, not just parenthesis. With out the comma, (1) == 1. To get your desired output you need:

b1 = np.array([(1,), (1,)])
b1.shape
# (2, 1)
Mark
  • 90,562
  • 7
  • 108
  • 148