# tuples.py # Remember that a string is an ordered set of characters? Also remember # that a list is an ordered set of values of any type? We said both strings # and lists and other things that behave like ordered sets are called # sequences. Also remember that strings are immutable and lists are mutable? # # A tuple, like a list, is a sequence of items of any type. Unlike lists, # however, tuples are immutable. # Since a tuple is a data structure, think about four things that I talked # about when I introduced strings to you: # (1) How do you create one? # (2) How do you access an element in it? # (3) How do you modify an element in it in place? It is immutable! # (4) How do you destroy it when we don't need it any more? (don't worry # about it) # Let's see some tuples and related functions that we can use to manipulate # tuples. Also think about where tuples would be useful as you write your # programs. # Syntactically, a tuple is a comma-separated sequence of values. a = 2, 3, 4, 6, 7, 10 print a # Although it is not necessary, it is conventianal to enclose tuples in # parentheses: b = (20, 30, 40, 60, 70, 100) print b # To create a tuple with a single element, we have to include the final comma. # Without the commna, Python treats (5) as an integer in parenthses. tup = (22,) print type(tup) # Syntax issues aside, tuples support the same sequence operations as strings # and lists. The index operator selects an element from a tuple: tup = ('a', 'b', 'c', 'd', 'e') print tup[0] # And the slice operator selects a range of elements: print tup[1:3] # As expected you can't modify an element in place - immutable! # tup[2] = 'K' # this would produce an eror. What kind of error? Try it! # Althouhg we can't replace an element in place, we can rebind the variable # with a new tuple: tup = ('a', 'b', 'K', 'd', 'e') # Tuple assignment is convenient. To swap the values of a and b we can do # the following: a, b = b, a # Tuples as return values # # Functions can return tuples as return values. For example, we could write # a function that swas two parameters like this: def swap(x, y): return y, x # Then do the following to swap: a, b = swap(a, b) # What would this definition of swap (called swapbad) do? # def swapbad(x, y): x, y = y, x # If we call this function like this: swapbad(a, b) # then changing x inside swapbad makes x refer to a different value, # but it has no effect on a in __main__. Similarly, changing y has # no effect on b. # This would do the right thing, but a function like this would be # redundant. I am using this example to illustrate the local variables # and their relationship with variables outside of a funciton. def swapgood(x, y): x, y = y, x return x, y a, b = swapgood(a, b) # I will stop on tuples here. If you want to learn more on tuples, read # Chapter 11 of [DEM]