Tuples are created in a similar fashion to lists, except that there is no need for square brackets surrounding the value. When the python interpreter displays a tuple, it always surrounds it with parentheses; you can use parentheses when inputting a tuple, but it's not necessary unless the tuple is part of an expression. This creates a slight syntactic problem when creating a tuple with either zero or one element; python will not know you're creating a tuple. For an empty (zero-element) tuple, a pair of empty parentheseis (()) can be used. But surrounding the value with parentheses is not enough in the case of a tuple with exactly one element, since parentheses are used for grouping in arithmetic expression. To specify a tuple with only one element in an assignment statement, simply follow the element with a comma. In arithmetic expressions, you need to surround it with parentheses, and follow the element with a comma before the closing parenthesis.
For example, suppose we wish to create a new tuple which concatenates the value 7 to the end of an existing tuple:
>>> values = 3,4,5 >>> values + (7) Traceback (innermost last): File "<stdin>", line 1, in ? TypeError: illegal argument type for built-in operation >>> values + (7,) (3, 4, 5, 7) >>> newvalue = 7, >>> values + newvalue (3, 4, 5, 7)Without the closing comma, python regards the value (7) as just a single number, and raises a TypeError exception when we try to concatenate it to an existing tuple. The closing comma identifies the expression as a single-element tuple, and concatenation can be performed.
Like lists, the contents of tuples are arbitrary. The only difference is that lists are mutable and tuples are not.