1
(0,)==(0)
False

What does , in (0,) means and when it is usefull to have that kind of tuple instead of the regular tuple like (0)?

I thought it might mean that item in index 1 is None but thats not the case :

(0,)[1]
Traceback (most recent call last):
  File "<input>", line 1, in <module>
IndexError: tuple index out of range

Also, if i want (0,1,) to become (0,1) how do i manipulate it?

EDIT:

Maybe i over simplified the example used for my problem, this is my original problem :

(('Suggest', 1.0), 65)==((('Suggest', 1.0),), 65)
False

So i guess python doesnt interpert ('Suggest', 1.0) as mathematical expression does it?

Ofek Ron
  • 8,354
  • 13
  • 55
  • 103

1 Answers1

4

(0) wouldn't be interpreted by Python as a tuple, but instead as a numeric expression (like (1+2) except without any math operation). The trailing comma is used to tell Python that it is explicitly a 1-element tuple.

>>> type((0))
<type 'int'>
>>> type((0,))
<type 'tuple'>

(0) evaluates to a number:

>>> (0) == 0
True

(0,) evaluates to a tuple, which is not a number...

(0,) == 0 False

...but is a tuple.

>>> (0,) == tuple([0])
True

This isn't specific to numbers, either - (expression) will always be equivalent to expression, while (expression,) will always be a single-element tuple with the first (and only) item in the tuple being the result of expression.

Amber
  • 507,862
  • 82
  • 626
  • 550
  • please see my edit – Ofek Ron Feb 01 '19 at 06:49
  • @OfekRon `("foo")` is still different from `("foo",)` - without the `,` the parentheses get ignored in favor of the expression inside them. With the `,` it defines a tuple. – Amber Feb 02 '19 at 05:54