What does a python tuple do?

The following code does not print what I expect:

#!/usr/bin/env python print type(1,) a = 1, print type(a) 

Here is the result:

 <type 'int'> <type 'tuple'> 

I understand that a comma turns into a tuple. But if so, then how does the original print not print the tuple type, but int?

+4
source share
3 answers

Since the tuple syntax inside the function call is also a way to pass parameters:

 >>> print type(1,2) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: type() takes 1 or 3 arguments >>> print type((1,)) <type 'tuple'> >>> a = 1, >>> type(a) <type 'tuple'> 

This is the syntax ambiguity for python that it solves by deciding that you are trying to pass a parameter (if you ask me, it should be a syntax error, though).

 >>> print type(1,) >>> print type(1) 

Same.

+9
source

type() is a function, so the python parser will pass everything between the brackets of the type function call as a tuple of arguments to this function.

Thus, to pass a literal tuple to a function call, you always need to add a bracket to the tuple so that the parser recognizes it as such:

 print type((1,)) 
+1
source

Because it is not enclosed in parentheses: type((1,))

Without additional parentheses in this context, it is considered as a simple list of parameters, and the end semicolon is simply ignored.

0
source

All Articles