Reputation: 24661
I noticed that some numpy operations take an argument called shape
, such as np.zeros
, whereas some others take an argument called size
, such as np.random.randint
. To me, those arguments have the same function and the fact that they have different names is a bit confusing. Actually, size
seems a bit off since it really specifies the .shape
of the output.
Is there a reason for having different names, do they convey a different meaning even though they both end up being equal to the .shape
of the output?
Upvotes: 26
Views: 29029
Reputation: 5858
Random array:
[[-2. -1. 0. 1. 2.]
[-2. -1. 0. 1. 2.]
[-2. -1. 0. 1. 2.]]
Here is the difference:
print(your_np_arr.shape) # (3, 5)
print(your_np_arr.size) # 15
Upvotes: 0
Reputation: 39
Because you are working with a numpy array, which was seen as a C array, size
refers to how big your array will be. Moreover, if you can pass np.zeros(10)
or np.zeros((10))
. While the difference is subtle, size
passed this way will create you a 1D array. You can give size=(n1, n2, ..., nn)
which will create an nD array.
However, because python users want multi-dimensional arrays, array.reshape
allows you to get from 1D to an nD array. So, when you call shape
, you get the N dimension shape of the array, so you can see exactly how your array looks like.
In essence, size
is equal to the product of the elements of shape
.
EDIT: The difference in name can be attributed to 2 parts: firstly, you can initialise your array with a size. However, you do not know the shape of it. So size
is only for total number of elements. Secondly, how numpy was developed, different people worked on different parts of the code, giving different names to roughly the same element, depending on their personal vision for the code.
Upvotes: 1
Reputation: 16224
Shape
relates to the size of the dimensions of an N-dimensional array.
Size
regarding arrays, relates to the amount (or count) of elements that are contained in the array (or sometimes, at the top dimension of the array - when used as length).
For example, let a
be a matrix
1 2 3 4
5 6 7 8
9 10 11 12
the shape of a
is (3, 4)
, the size of a
is 12 and the size of a[1]
is 4.
Upvotes: 14