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条回答
Deceive 欺骗
2楼-- · 2019-07-01 23:21

This is such a common question that the Python Wiki has a page dedicated to it:

One Element Tuples

One-element tuples look like:

1,

The essential element here is the trailing comma. As for any expression, parentheses are optional, so you may also write one-element tuples like

(1,)

but it is the comma, not the parentheses, that define the tuple.

查看更多
混吃等死
3楼-- · 2019-07-01 23:21

That is normal behavior in Python. You get a Tuple with one element. The notation (1,) is just a reminder that you got such a tuple.

查看更多
Anthone
4楼-- · 2019-07-01 23:24

What you are getting is a tuple. When there is only a single element, then it has to be represented with a comma, to show it is a tuple.

Eg)

>>> a = (1)
>>> type(a)
<type 'int'>
>>> a = (1,)
>>> type(a)
<type 'tuple'>
>>>

The reason is, when you do not use a comma when there is only one element, the interpreter evaluates it like an expression grouped by paranthesis, thus assigning a with a value of the type returned by the expression

查看更多
劫难
5楼-- · 2019-07-01 23:25

That is how tuples are formed in python. Using just (1) evaluates to 1, just as much as using (((((((1))))))) evaluates to ((((((1)))))) to (((((1))))) to... 1.

Using (1,) explicitly tells python you want a tuple of one element

查看更多
beautiful°
6楼-- · 2019-07-01 23:27

(1) is just 1 in grouping parentheses - it's an integer. (1,) is the 1-element tuple you want.

查看更多
你好瞎i
7楼-- · 2019-07-01 23:27

The output (1,) is fine. The , is to mark a single element tuple.

If

a = (1) 

a is really a integer

If

a = (1, )

Then a is a tuple.

查看更多
登录 后发表回答