Tuple declaration in Python

江枫思渺然 提交于 2021-01-27 04:39:41

问题


In python, one can declare a tuple explicitly with parenthesis as such:

>>> x = (0.25, 0.25, 0.25, 0.25)
>>> x
(0.25, 0.25, 0.25, 0.25)
>>> type(x)
<type 'tuple'>

Alternatively, without parenthesis, python automatically packs its into a immutable tuple:

>>> x = 0.25, 0.25, 0.25, 0.25
>>> x
(0.25, 0.25, 0.25, 0.25)
>>> type(x)
<type 'tuple'>

Is there a pythonic style to declare a tuple? If so, please also reference the relevant PEP or link.

There's no difference in the "end-product" of achieving the tuple but is there a difference in how the tuple with and without parenthesis are initialized (in CPython)?


回答1:


From practical point of view it's best to always use parenthesis as it contributes to readability of your code. As one of the import this moto says:

"Explicit is better then implicit."

Also remember, that when defining one-tuple you need a comma: one_tuple = (15, ).




回答2:


There's no particular "pythonic" way. Except for the empty parenthesis the parenthesis is just a parenthesis (which controls precedence). That is the expression x = 1,2,3 is same as x = (1,2,3) (as the tuple is created before assignment anyway).

Where it may differ is where the order matters. For example if l is a list or tuple the expression 1,2,l.count(1) would mean that l.count is called before the tuple is created while (1,2,l).count(1) first creates the tuple then it's count is called. It's the same parenthesis as in (2+3)*4 (which says add first and multiply then).

The only case where the parenthesis is required is when creating the empty tuple. This is done by fx the expression x = () because there's no other way. And the only case where trailing comma is mandatory is when creating a tuple of length one (ie x = 1,) since it would be impossible to distinguish from the element 1 otherwise.



来源:https://stackoverflow.com/questions/34809173/tuple-declaration-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!