alvas
alvas

Reputation: 122022

Tuple declaration in Python

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)?

Upvotes: 8

Views: 4565

Answers (2)

skyking
skyking

Reputation: 14360

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.

Upvotes: -1

Nikita
Nikita

Reputation: 6331

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, ).

Upvotes: 5

Related Questions