Type(3,) returns an integer instead of a tuple in python, why?

Go To StackoverFlow.com

5

type(3,) returns the int type, while

t = 3,
type(t)

returns the tuple type. Why?

2012-04-03 21:39
by Bentley4


13

Inside the parentheses that form the function call operator, the comma is not for building tuples, but for separating arguments. Thus, type(3, ) is equivalent to type(3). An additional comma at the end of the argument list is allowed by the grammar. You need an extra pair of parens to build a tuple:

>>> def f(x):
...     print x
... 
>>> f(3)
3
>>> f(3,)
3
>>> f((3,))
(3,)
2012-04-03 21:43
by Sven Marnach


6

The builtin type() is a function, so the comma is being parsed as an argument separator rather than a tuple constructor.

>>> type(3,)
<type 'int'>

>>> type((3,))
<type 'tuple'>
2012-04-03 21:42
by Russell Borogove
Regardless of how many arguments f takes, the comma will be parsed as an argument separator - Aaron Dufour 2012-04-03 21:43
You're right - I just verified that on my end. Will edit - Russell Borogove 2012-04-03 21:43


2

I suspect Python ignores a trailing comma in function arguments:

def f (a):
    print a
    print type(a)

>>> f(3,)
3
<type 'int'>

Using comma-separated values without parentheses to create a tuple is a trick that doesn't work everywhere. List comprehensions is a good example:

>>> [a,a*2 for a in range(4)]
  File "<stdin>", line 1
    [a,a*2 for a in range(4)]
             ^

You have to do this:

>>> [(a,a*2) for a in range(4)]
[(0, 0), (1, 2), (2, 4), (3, 6)]

List unpacking works fine, though, so it's a bit variable where unbounded, comma-separated values are allowed:

>>> [(a,b) for a, b in zip(range(4),range(4))]
[(0, 0), (1, 1), (2, 2), (3, 3)]
2012-04-03 21:49
by Gary Fixler


0

In func(bunch_of_args) you are allowed to follow the last arg with a comma, just like in

alist = [1, 2, 3, ]
2012-04-03 21:50
by John Machin
Ads