Strange Tuple syntax

Hello All

If tuple has a single element, I find the syntax to be strange. It has a comma after the single element

arr1 = np.array(data)

Output is as follows


Is this expected ?


It is not a Tuple. It is an Array. And also you printed the shape of that Array. the (5, ) means . it is a vector with only 5 values in it.

No Thats not correct. It is a Tuple

Please execute this and you will see it is a Tuple (also pretty evident from the fact it printed with simple brackets)

data = [1,2,3,4,5]

arr_ = np.array(data)


Yes, @hari.yajurveda tuples with one element has a comma at the end. Hence it looks like (5,) . Hope this helps!!

Sorry, the problem was I didn’t read your question well. You’ve asked “is this expected”. Yeah it is expected.
for eg:

>>> arr_ = np.array([[1, 2, 3, 4, 5]])
>>> arr_.shape
(1, 5)

If you’ve created array passing a single list. You’ll get a 1-d array. That’s why you get an output like that. If you nested it in another list. you’ll get the output (1, 5).

Yes. You are right that it is a tuple since the shape of a Numpy array is a tuple.

Tuples with one element are printed with a comma following them. The reason is that Python favours printing objects in a format similar to what you would type as Python code to get that object.
If you have a tuple with one element, say the string 'tuples', then Python cannot (according to the above principle) print it as ('tuple'), because if you typed that as Python code, you would get the string 'tuple', not a tuple with one element. (It would be assumed that you had added the brackets ( ) for clarity.)
So instead, Python prints it out with an extra comma. In fact, you can check that if you type ('tuple',) as Python code, you will get a tuple with 'tuple' as its only element, instead of a string.

Thank you very much. This was very helpful