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

type(3,) returns type int, and

t = 3,
type(t)

returns the type of tuple. Why?

+5
source share
4 answers

In parentheses that make up the function call operator, the comma is not intended for constructing tuples, but for separating arguments. So it is type(3, )equivalent type(3). An extra comma at the end of the argument list is allowed by the grammar. To create a tuple, you need an additional pair of pairs:

>>> def f(x):
...     print x
... 
>>> f(3)
3
>>> f(3,)
3
>>> f((3,))
(3,)
+13
source

Inline type()is a function, so the comma is parsed as an argument delimiter, not a tuple constructor.

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

>>> type((3,))
<type 'tuple'>
+6
source

, Python :

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

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

- , . - :

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

:

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

, , , :

>>> [(a,b) for a, b in zip(range(4),range(4))]
[(0, 0), (1, 1), (2, 2), (3, 3)]
+2
source

As func(bunch_of_args)you are allowed to follow the last argument with a comma, as in the

alist = [1, 2, 3, ]
0
source

All Articles