Tuples

A tuple consists of a number of values separated by commas. The difference between a list and a tuple is that tuples are immutable i.e they cannot be changed while lists are mutable.

Although not necessary, to define a tuple we  commonly encloses sequences of values in parenthesis.

python">tuple1 = 12345, 54321, 'hello!'

>>> print tuple1

(12345, 54321, ‘hello!’)

Empty tuples are constructed by an empty pair of parentheses; 

>>> emptyTuple = ()

A tuple with one item is constructed by following a value with a comma. 

>>> singleton = ('hello',)    # <-- note trailing comma

Accessing Values in Tuples

To access values in tuple, use square brackets for slicing along with the index or indices to obtain value available at that index. For example −

python">tup1 = ('maths', 'biology', 2010, 2000);

tup2 = (1, 2, 3, 4, 5, 6, 7 );

print "tup1[0]: ", tup1[0];

print "tup2[1:5]: ", tup2[1:5];

When the code above is executed, it produces the following result −

python">tup1[0]:  maths

tup2[1:5]:  [2, 3, 4, 5]

Updating Tuples

Tuples are immutable, this means you cannot update or change the values of tuple elements. You are able to take portions of existing tuples to create new tuples as the following example demonstrates −

python">tup1 = (12, 34.56);

tup2 = ('abc', 'xyz');

# Following action is not valid for tuples

# tup1[0] = 100;

# So let's create a new tuple as follows

tup3 = tup1 + tup2;

print tup3;

When the code above  is executed, it produces the following result −

(12, 34.56, 'abc', 'xyz')

Deleting a Tuple

Since tuples are immutable you cannot remove individual elements in tuple. To explicitly remove an entire tuple, just use the del statement. For example:

python"># Deleting a Tuple 

Tuple1 = (0, 1, 2, 3, 4) 

del Tuple1 

print(Tuple1) 

When the above code is executed you get an an exception error since tuple1 has been deleted and does not exist:

python">Traceback (most recent call last):

  File "", line 1, in 

NameError: name 'Tuple1' is not defined

Built-in Tuple Functions

Python includes the following tuple functions −

Function with Description
cmp(tuple1, tuple2) – Compares elements of both tuples.
len(tuple) – Gives the total length of the tuple.
max(tuple) – Returns item from the tuple with max value.
min(tuple) – Returns item from the tuple with min value.
tuple(seq) – Converts a list into tuple.