Lecture Notes
Introduction to Programming and Algorithm Design (COP-1000)


This chapter discusses tuples a sequence of values where each value is identified by an integer index, like a list. The values in a tuple are called elements, which, like those in lists, can be of any type. The difference between tuples and lists is that a tuple is immutable, whereas a list is mutable.

Tuples are immutable

  • We have covered two sequence types available in Python: strings and lists
  • A third type is a tuple, whose elements can be any type, but which is immutable
  • A tuple is written as a comma separated sequence of values, usually (but syntactically not required to be) enclosed in parentheses:

       >>> t = (-11, "Funtwo", 8.83)
       >>> type(t)
       <type 'tuple'>
       >>> u = (17,)      # trailing comma ...
       >>> type(u)
       <type 'tuple'>     # makes u a tuple
       >>> v = (17)       # no trailing comma ...
       >>> type(v)     
       <type 'int'>       # makes v an int
  • A tuple can also be created with the built-in function tuple: if the argument is a sequence type, the result is a tuple whose elements are the elements of the sequence
       >>> x = tuple()
       >>> print x
       ()       # the empty tuple
       >>> y = tuple("Adios")
       >>> print y
       ('A', 'd', 'i', 'o', 's')
  • Tuples can be indexed and sliced:

       >>> print t[1]
       >>> print t[1:]
       ('Funtwo', 8.8300000000000001)
  • Tuples can be concatenated and repeated:

       >>> print t + u
       (-11, 'Funtwo', 8.8300000000000001, 17)
       >>> print u * 4
       (17, 17, 17, 17)
  • You can get the number of elements of a tuple with the len() function:

       >>> len(t)
  • You can traverse a tuple with the for keyword:

       >>> for var in t:
               print var

  • Use the in or not in operators to determine if a value is an element of a tuple:

       >>> "Funtwo" in t
       >>> -11 not in t
  • But you can't change or delete an element of a tuple:

       >>> t[1] = "Funthree"

       Traceback (most recent call last):
       File "<pyshell#27>", line 1, in -toplevel-
       t[1] = "Funthree"
       TypeError: object does not support item assignment

       >>> del t[2]

       Traceback (most recent call last):
       File "<pyshell#28>", line 1, in -toplevel-
       del t[2]
       TypeError: object doesn't support item deletion

Tuple assignment

  • Because of the nature of tuples, we can use them to assign values to multiple variables in a single assignment statement:

       >>> x, y, z = 1, 2, 3
       >>> print x, y, z
       1 2 3
  • You can also input multiple values this way, as long as the user separates the values with a comma:

       >>> a, b = input("Enter two numbers: ")
       Enter two numbers: -78, 15
       >>> print a, b
       -78 15
  • We can even swap the value of two variables without using a temporary variable:

       >>> a, b = b, a
       >>> print a, b
       15 -78
    Note: this is only syntactically possible in Python; most other languages, like C, C++ and Java require you to use a temporary variable to accomplish a swap:

       >>> temp = a
       >>> a = b
       >>> b = temp
       >>> print a, b
       -78 15
    What happens if you don't use a temporary variable?

       >>> a = b
       >>> b = a
       >>> print a, b
       15 15

Tuples as return values

  • A fruitful function can return any data type, including a tuple
  • See example program cylData.py

Variable-length argument tuples

  • So far we have written and used only functions that take a fixed number of arguments to fill a fixed number of parameters
  • To write a function that will accept a variable number of arguments, use a parameter name that begins an asterisk (*), which gathers arguments into a single tuple
  • See example program avg_all.py

Lists and tuples

  • Python has a built-in function zip that combines two or more sequences into a single list of ttuples, with one element from each sequence; if the sequences are not of the same length, the result is the length of the shortest sequence
  • See example program zip_list.py
  • When you traverse a list of tuples, you can use multiple variables to assume the value of each of the elements in each tuple in the list
  • See example program zip_list2.py

Dictionaries and tuples

  • The dictionary method items returns a list of tuples, where each tuple is a key-value pair from the dictionary
  • see example program items.py
  • Combining dict and zip is a simple way to create a dictionary
  • See example program create_dict.py
  • Tuples can be used as dictionary keys
  • See example program directory.py
    • Uses a tuple (Last name, first name) as key, phone number as value
    • Uses % formatting operator (%s to display a string, -30 is left-justified in a 30-character wide field)

Comparing tuples

  • Tuples can be compared with the normal comparison operators; the comparison is done element-by-element, left-to-right:

>>> (1, 23, -3) < (1, 400, -2000000)
>>> (1, 23, -3) < (1, 400)

Sequences of sequences

  • Python provides the flexibility to create sequences of sequences: lists of lists, lists of strings, lists of tuples, tuples of strings, etc.
  • Which one to use? This table compares some of the properties of each sequence type:
Property String List Tuple
Delimeter " " [ ] ( )
Elements are ... chars any type any type
Traversable? Yes Yes Yes
Operators in/not? Yes Yes Yes
Index/slice? Yes Yes Yes
Mutable? No Yes No
Use as dictionary key? Yes No Yes
Use sort/reverse methods? No Yes No
 Updated: 12.13.2010