Reputation: 6101
a tuple is a comma-separated list of values
so the valid syntax to declare a tuple is:
tup = 'a', 'b', 'c', 'd'
But what I often see is a declaration like this:
tup = ('a', 'b', 'c', 'd')
What is the benefit of enclosing tuples in parentheses ?
Upvotes: 11
Views: 2421
Reputation: 3745
Those are good answers! Here's just an additional example of tuples in action (packing/unpacking):
If you do this
x, y = y, x
what's happening is:
tuple_1 = (y, x)
(x, y) = tuple_1
which is the same as:
tuple_1 = (y, x)
x = tuple_1[0]
y = tuple_1[1]
In all these cases the parenthesis don't do anything at all to the python. But they are helpful if you want to say to someone reading the script "hey! I am making a tuple here! If you didn't see the comma I'll add these parenthesis to catch your eye!"
Of course the answers about nested tuples are correct. If you want to put a tuple inside something like a tuple or list...
A = x, (x, y) # same as (x, (x, y))
B = [x, (x, y)]
Upvotes: 2
Reputation: 2723
From the Python docs:
... so that nested tuples are interpreted correctly. Tuples may be input with or without surrounding parentheses, although often parentheses are necessary anyway (if the tuple is part of a larger expression).
Example of nested tuples:
tuple = ('a', ('b', 'c'), 'd')
Upvotes: 10
Reputation: 14358
The parentheses are just parentheses - they work by changing precedence. The only exception is if nothing is enclosed (ie ()
) in which case it will generate an empty tuple.
The reason one would use parentheses nevertheless is that it will result in a fairly consistent notation. You can write the empty tuple and any other tuple that way.
Another reason is that one normally want a literal to have higher precedence than other operations. For example adding two tuples would be written (1,2)+(3,4)
(if you omit the parentheses here you get 1,2+3,4
which means to add 2 and 3 first then form the tuple - the result is 1,5,4
). Similar situations is when you want to pass a tuple to a function f(1,2)
means to send the arguments 1 and 2 while f((1,2))
means to send the tuple (1,2)
. Yet another is if you want to include a tuple inside a tuple ((1,2),(3,4)
and (1,2,3,4)
are two different things.
Upvotes: 9