Reputation: 14619
Elsewhere in the universe, a question came up regarding the use of parens around tuple
s.
"is there any advantage/disadvantage to declaring tuples by
x = 1, 2
as opposed tox = (1, 2)
? ... in regards to speed and memory allocation"
Upvotes: 2
Views: 85
Reputation: 14619
Normally I'd suggest evaluating speed empirically with timeit
but this struck me as something that's truly equivalent.
Sure enough, the dis
assembly confirms this:
Here's x = 1, 2
6 0 LOAD_CONST 3 ((1, 2))
3 STORE_FAST 2 (x)
6 LOAD_CONST 0 (None)
9 RETURN_VALUE
and x = (1, 2)
:
9 0 LOAD_CONST 3 ((1, 2))
3 STORE_FAST 2 (x)
6 LOAD_CONST 0 (None)
9 RETURN_VALUE
Just in case folks were curious if somehow the similarity was only present in tuple
s consisting of literals, I also did x = a, b
:
12 0 LOAD_FAST 0 (a)
3 LOAD_FAST 1 (b)
6 BUILD_TUPLE 2
9 STORE_FAST 2 (x)
12 LOAD_CONST 0 (None)
15 RETURN_VALUE
and x = (a, b)
:
15 0 LOAD_FAST 0 (a)
3 LOAD_FAST 1 (b)
6 BUILD_TUPLE 2
9 STORE_FAST 2 (x)
12 LOAD_CONST 0 (None)
15 RETURN_VALUE
As was cited in the source article, Python's Fine Manual covers the topic of optional parens:
As you see, on output tuples are always enclosed in parentheses, so that nested tuples are interpreted correctly; they may be input with or without surrounding parentheses, although often parentheses are necessary anyway (if the tuple is part of a larger expression).
Let's zoom in on why exactly they're "often ... necessary anyway" -- it's a matter of operator precedence. Just like conventional written arithmetic has an order of operations, so do programming languages like Python. It helps us distinguish 12 + 1 / 2
from (12 + 1) / 2
. So in this case, we often need parentheses around tuple
elements that are more complex than a simple name or literal. So we can see below in these examples two different ways of interpreting expressions which use tuples. Since the precedence of commas is lower than the multiplication operator (and their associativity is the same), the multiplication happens first when there are no parentheses to provide more explicit ordering.
>>> 12 * 4, 5
(48, 5)
>>> 12 * (4, 5)
(4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5)
A footnote regarding parens and tuples, also from The Fine Manual:
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.
Resource: https://gist.github.com/androm3da/8a646fbe817d576b1f0d
Upvotes: 3