Reputation: 2389
I have a NumPy
array
that is of size (3, 3). When I print shape of the array
within __main__
module I get (3, 3)
. However I am passing this array to a function and when I print its size in the function I get (3, )
.
Why does this happen?
Also, what does it mean for a tuple to have its last element unspecified? That is, shouldn't (3, )
be an invalid tuple in the first place?
Upvotes: 1
Views: 1263
Reputation: 1322
To answer your second question:
Tuples in Python are n-dimensional. That is you can have a 1-2-3-...-n
tuple. Due to syntax, the way you represent a 1-dimensional
tuple is ('element',)
where the trailing comma is mandatory. If you have ('element')
then this is just simply the expression inside the parenthesis. So (3) + 4 == 7
, but (3,) + 4 == TypeError
. Likewise ('element') == 'element'.
To answer your first question:
You're more than likely doing something wrong with passing the array around. There is no reason for the NumPy array to misrepresent itself without some type of mutation to the array.
Upvotes: 2
Reputation: 35059
It is hard to tell why a function call would reshape a numpy array without seeing the code.
On the second question, that is the standard notation for a single-element tuple - the comma, rather than the brackets, is what makes it a tuple. Consider (3+3) * 2
- if the brackets made a tuple, then that whole expression would be invalid since you can't multiply a tuple by an int. More generally, Python allows trailing commas all over the place:
>>> (3,3,) == (3,3)
True
This also works for lists, dictionaries and function calls - basically, everywhere where Python expects comma-separated elements, a trailing comma is valid.
Upvotes: 2
Reputation: 235984
A tuple like this: (3, )
means that it's a tuple with a single element (a single dimension, in this case). That's the correct syntax - with a trailing ,
because if it looked like this: (3)
then Python would interpret it as a number surrounded by parenthesis, not a tuple.
It'd be useful to see the actual code, but I'm guessing that you're not passing the entire array, only a row (or a column) of it.
Upvotes: 2