Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are tuples enclosed in parentheses?

Tags:

python

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 ?

like image 454
Trevor Avatar asked Feb 06 '16 12:02

Trevor


2 Answers

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')
like image 176
Genti Saliu Avatar answered Sep 21 '22 15:09

Genti Saliu


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.

like image 44
skyking Avatar answered Sep 21 '22 15:09

skyking