Tuple declaration in Python
Asked Answered
D

2

8

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

Dialect answered 15/1, 2016 at 10:37 Comment(4)
Related: #16018311. (There isn't any difference - the commas define the tuple, parentheses are optional but often useful.)Niemeyer
Whoops wrong it should be CPythonDialect
Hmm...I'd prefer x = (0.25, 0.25, 0.25, 0.25) because it's clear that x is a tuple. And that's more like a real tuple (I mean, like the output).Bordereau
Err sorry I had closed it as duplicate of #16018311 but it's not really. And Nikita's answer is the right one.Nicotiana
F
5

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

Fecund answered 15/1, 2016 at 10:45 Comment(6)
The point on one element tuple is not correct. x = 1,; x gives (1,)Dialect
@alvas: Nikita says that: When defining one-tuple you need a comma. Not about the parenthesis.Bordereau
@KevinGuan Ah, I misunderstood.Dialect
x=1, and x=(1,) both legal tuples, type(x) will give <class 'tuple'>. But x=1 and x=(1) are just integers, type(x) will give <class 'int'> here.Fecund
And a zero element tuple needs the parens: ().Bertine
Interesting (,) is illegal to declare a zero tuple.Dialect
D
-1

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.

Dinahdinan answered 15/1, 2016 at 11:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.