Introductory Programming in Python: Lesson 10
Tuples

[Prev: Lists] [Course Outline] [Next: Dictionaries]

Tuples as Immutable Lists

In many ways tuples and lists are very similar. In fact tuples are basically immutable lists, that is, lists which cannot be changed. All the same operators work on them; concatenation, repetition, subscription, and slicing. All the comparison operators work in the same way: equivalence, less than, greater than, 'is'. However, assignments to tuples cannot be made as they are immutable, or unchangeable. Once a tuple has been formed, it cannot be changed. New tuples can be formed from others using concatenation, repetition, etc... but the operand tuples remain unchanged by the operators.

Forming a Tuple

Tuples are technically formed in python using a comma, although most often they are found recorded in round braces. Tuples can be of any length, and have their elements indexed from 0 to len(tuple)-1.

Python 2.4.3 (#1, Oct	2 2006, 21:50:13) 
[GCC 3.4.6 (Gentoo 3.4.6-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 1, 2
(1, 2)
>>> 1, 
(1,)
>>> (1)
1
>>> (1, 2)
(1, 2)
>>> ("Tuples", "can", "have", "elements", "of", "more", "than", 1, "type")
('Tuples', 'can', 'have', 'elements', 'of', 'more', 'than', 1, 'type')
>>>

Using Tuples

Breaking it down we get to the old grind of operators, and in the case of tuples a a few new ideas. Let's get the operators out of the way! If both 'a' and 'b' are tuples, 'v' is any expression, and 'i', 'j', and 'k' are integers then

For completeness sake, here are examples ...

Python 2.4.3 (#1, Oct	2 2006, 21:50:13)
[GCC 3.4.6 (Gentoo 3.4.6-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = (1,2,3)
>>> a+(4,5)
(1, 2, 3, 4, 5)
>>>
>>> (4,5)+a
(4, 5, 1, 2, 3)
>>> a*2
(1, 2, 3, 1, 2, 3)
>>>
>>> (1,)*2+2*(2,)
(1, 1, 2, 2)
>>>
>>> ((1,)*2,(2,)*2)
((1, 1), (2, 2))
>>>
>>> (1,)*2*3
(1, 1, 1, 1, 1, 1)
>>>
>>> a[0]
1
>>> a[1:3]
(2, 3)
>>> a = (1, 2, 3, 4, 5)
>>> a[0:6:2]
(1, 3, 5)
>>> a[:3]
(1, 2, 3)
>>> a[3:]
(4, 5)
>>> a[:]
(1, 2, 3, 4, 5)
>>>

The comparison of tuples to other tuples happens in the same way as lists to lists.

If tuples have a subset of the functionality of lists, why ever use them? What can they do that lists cannot. Well, actually they provide a very convenient way to package multiple variables together for passing to a function as a parameter, or more likely returning from a function. Technically speaking functions can only return one value, but since a tuple is a single 'value' no matter how many elements it contains, a tuple could be used in a function that returns a two-component piece of data, for example an x:y coordinate. Even better, is that python implicitly unpacks tuples. By unpack we mean the assignment of multiple variables at once to their respective (based on position) elements in a tuple, for example

>>> t = (1, 2, 3)
>>> a, b, c = t
>>> a
1
>>> b
2
>>> c
3
>>>

And since tuples are formed by a comma, this provides us with a nifty little method to swap the values of two variables,

>>> a = 1
>>> b = 2
>>> b, a = a, b
>>> a
2
>>> b
1
>>>

Exercises

  1. If the use of a comma forms a tuple, then how do we indicate a tuple as an expression to the print statement, rather than its elements as separate expressions?
  2. What is the difference between concatenation and addition of tuples? Why is the python plus operator for tuples a concatenation operator instead of an addition operator?
  3. The code a, b = b, a swaps the values of a and b. What would happen if added a third variable to the mix, c, as in a, b, c = b, c, a? What would happen if one repeated the statement indefinitely?
  4. Given a variable with the value of the empty tuple (a = ()), how does one 'append' an element to 'a'?
  5. Write a program that accepts a list of numbers terminated by a blank line. Print out the entered numbers as elements of a tuple, in the order they were entered.
  6. Given a list of tuples each specifying a subject name and a grade symbol ('A' - 'F') in the form [('Maths', 'D'), ('Comp Sci', 'B'), ('English', 'C'), ('French', 'A'), ('Science', 'B'), ('History', 'E')]:
    1. Write a program that prints out the subject with the highest mark.
    2. Write a program that outputs each subject and the grade symbol in the format 'subject: symbol', with each subject on a single line.
    3. Write a program that prints out a tab separated list of subjects on the first line, and the corresponding grades, also tab separated on the second line.
  7. Write a program that accepts a list of numbers terminated by a blank line, and stores the result in a tuple, a. Repeat the process to form a second user inputted tuple, b, making sure there are the same number of elements in b as in a. Print out the result of the mathematical addition (not concatenation) of the two tuples as a tuple.
  8. Write a program that reads a name and an age for a person, until the name is blank. As each name age pair is entered, store names in a list, and ages in another. Print a list of tuples of paired names and ages.
  9. Write a program that reads a name and an age for a person, until the name is blank. Once all names have been present the user with an option to list the entered people in alphabetical order, or in descending age order. For either choice, list each person's name followed by their age on a single line. Make sure you output the correct age for the correct person.
[Prev: Lists] [Course Outline] [Next: Dictionaries]