-1

I found strange thing about data type of integers with comma at the end of expression (see code below).

Code

a = -1,  # strange legal syntax

print('"a" has {} data type'.format(type(a)))

if type(a) == tuple:

    print(len(a))

else:

    print('It is not a tuple!')

print('If we print "-1," directly, without variable, then ... {}'.format(type(-1,)))

Questions:

Using Jupyter notebook & Spyder console I find different results. What is going on with this? What data type does the variable "a" has: int or tuple?

Shawn
  • 47,241
  • 3
  • 26
  • 60
Pavel
  • 394
  • 3
  • 3
  • 4
    where are you getting the "not a tuple" result? `a` would be tuple in both python2 and python3. – Zinki Oct 11 '18 at 08:52
  • Possible duplicate of [How to create a tuple with only one element](https://stackoverflow.com/questions/12876177/how-to-create-a-tuple-with-only-one-element). – jpp Oct 11 '18 at 09:38
  • `a` will **always** be a tuple, in *every* version of Python, regardless of whether or not you use a Jupyter notebook (or some other IDE) – juanpa.arrivillaga Jun 13 '22 at 21:50

2 Answers2

2

a (defined as a = 1, is a tuple, period - it's the comma that defines a literal tuple, not the parens (except for the empty tuple of course). But the expression type(-1,) yields int because the comma is parsed as being part of the function call syntax rule, which takes precedence over the literal tuple syntax rule. Adding parens around the type() argument - ie type((-1,)) will force the parser to first eval what's inside the inner parens - hence creating a tuple instead.

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
1

This

a = -1,

is equal to this

a = (-1,)

It is a tuple.