1

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?

1
  • 1
    (3,) means a tule with one element. x = (3, ) gives you a tuple, x=(3) will not give you a tuple Commented Mar 11, 2013 at 3:13

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.