>A Byte of Python

Tuple

Tuples are just like lists except that they are immutable (like strings) i.e. you cannot modify tuples. Tuples are defined by specifying items separated by commas within a pair of parentheses. Tuples are usually used in cases where a statement or a user-defined function can safely assume that the collection of values i.e. the tuple of values used will not change.

Here, the variable zoo refers to a tuple of items. We see that the len function can be used to get the length of a tuple as well. This also indicates that a tuple is a sequence as well.

We are now shifting these animals to a new zoo since the old zoo is being closed. Therefore, the new_zoo tuple contains some animals which are already there along with the animals brought over from the old zoo. Back to reality, note that a tuple within a tuple does not lose it's identity.

We can access the items in the tuple using the indexing operator just like we did for lists. We just specify the item's position within a pair of square brackets following the name of the tuple such as new_zoo[2]. In this case, this object is a tuple. So we can access items of this object as well using new_zoo[2][2].

Tuple with 0 or 1 items. An empty tuple is constructed by an empty pair of parentheses such as myempty = (). However, a tuple with a single item is not so simple. You have to specify it using a comma following the single item so that Python can differentiate between a tuple and a pair of parentheses used for grouping in an expression i.e. you have to specify singleton = (some_item , ) .

Tuples are most often used alongwith the print statement. An example will make this clear.