Python Programming/Tuples

A tuple in Python is much like a list except that it is immutable (unchangeable) once created. A tuple of hashable objects is hashable and thus suitable as a key in a dictionary and as a member of a set.

Overview
Tuples in Python at a glance:

Tuple notation
Tuples may be created directly or converted from lists. Generally, tuples are enclosed in parentheses.

A one item tuple is created by an item in parentheses followed by a comma:

Also, tuples will be created from items separated by commas.

Packing and Unpacking
You can also perform multiple assignment using tuples.

Note that either, or both sides of an assignment operator can consist of tuples.

The example above: article, noun, verb, adjective, direct_object = t is called "tuple unpacking" because the tuple t was unpacked and its values assigned to each of the variables on the left. "Tuple packing" is the reverse: t=article, noun, verb, adjective, direct_object. When unpacking a tuple, or performing multiple assignment, you must have the same number of variables being assigned to as values being assigned.

Operations on tuples
These are the same as for lists except that we may not assign to indices or slices, and there is no "append" operator.

For lists we would have had:

Tuple Attributes
Length: Finding the length of a tuple is the same as with lists; use the built in len method.

Conversions
Convert list to tuples using the built in tuple method.

Converting a tuple into a list using the built in list method to cast as a list:

Dictionaries can also be converted to tuples of tuples using the items method of dictionaries:

Uses of Tuples
Tuples can be used in place of lists where the number of items is known and small, for example when returning multiple values from a function. Many other languages require creating an object or container to return, but with Python's tuple assignment, multiple-value returns are easy:

This resulting tuple can be easily unpacked with the tuple assignment technique explained above:

Using List Comprehension to process Tuple elements
Occasionally, there is a need to manipulate the values contained within a tuple in order to create a new tuple. For example, if we wanted a way to double all of the values within a tuple, we can combine some of the above information in addition to list comprehension like this:

Exercises

 * 1) Create the list ['a', 'b', 'c'], then create a tuple from that list.
 * 2) Create the tuple ('a', 'b', 'c'), then create a list from that tuple. (Hint: the material needed to do this has been covered, but it's not entirely obvious)
 * 3) Make the following instantiations simultaneously: a = 'a', b=2, c='gamma'. (That is, in one line of code).
 * 4) Create a tuple containing just a single element which in turn contains the three elements 'a', 'b', and 'c'. Verify that the length is actually 1 by using the len function.