How to perfectly convert one-element list to tuple

2019-07-01 22:41发布

So I am trying to do this:

tuple([1])

The output I expect is :

(1)

However, I got this:

(1,)

But if I do this:

tuple([1,2])

It works perfectly! like this:

(1,2)

This is so weird that I don't know why the tuple function cause this result.

Please help me to fix it.

7条回答
祖国的老花朵
2楼-- · 2019-07-01 23:30

From the docs

6.2.3. Parenthesized forms

A parenthesized form is an optional expression list enclosed in parentheses:

parenth_form ::=  "(" [expression_list] ")" 
A parenthesized expression list yields whatever that expression list yields: if the list contains at least one comma, it yields a tuple; otherwise, it yields the single expression that makes up the expression list.

An empty pair of parentheses yields an empty tuple object. Since tuples are immutable, the rules for literals apply (i.e., two occurrences of the empty tuple may or may not yield the same object).

Note that tuples are not formed by the parentheses, but rather by use of the comma operator. The exception is the empty tuple, for which parentheses are required — allowing unparenthesized “nothing” in expressions would cause ambiguities and allow common typos to pass uncaught.

So (1,) really is a tuple

查看更多
登录 后发表回答