Up: Python

Tuples

slide 001 Hello, and welcome to the eleventh episode of the Software Carpentry lecture on Python. This episode introduces Python’s “other” kind of sequence data type.
slide 002 As we saw a few episodes ago, a list is a mutable sequence of values, which can be of any type.
slide 003 A tuple is simply an immutable sequence of heterogeneous values.
slide 004 I.e., a list whose entries can’t be changed after its creation.
slide 005 At first or even second glance, it may seem strange to have tuples in the language—why provide a less general kind of collection?
slide 006 The full explanation will have to wait for the lecture on sets and dictionaries.
slide 007 But tuples allow us to do a few useful things even before we get that far.
slide 008 In Python, we create tuples using parentheses () instead of square brackets [].
slide 009 We still index them with square brackets, though, because everything in Python that’s indexed uses square brackets.
slide 010 For example, here’s a tuple containing the first four prime numbers. Just as with a list, primes[0] is its first element, and primes[-1] is its last.
slide 011 The empty tuple is written as, well, empty parentheses, and has a length of 0.
slide 012 If we want to create a tuple of just one value, though, we have to put a comma after that value and before the closing parenthesis. It looks a little odd…
slide 013 …but otherwise, (5) would be ambiguous: mathematically, it’s the same as (2+3).
slide 014 This trailing comma is easy to forget, and is one of Python’s few syntactic warts.
slide 015 The good news is, we don’t need the parentheses if it’s clear from context that we’re constructing a tuple.
slide 016 For example, we can create our tuple of primes just by putting commas between the four values, as shown here.
slide 017 The neat thing is, if we put a tuple of variables on the left side of an assignment, we can assign multiple values at once.
slide 018 For example, this statement sets the values of left, middle, and right all in one go.
slide 019 We can check that it worked by printing those variables out.
slide 020 But remember: with great power comes great responsibility. Initializing thirty-odd variables at once this way is probably not going to make your programs more readable…
slide 021 This same trick—tuple-to-tuple assignment—allows functions to return several values at once.
slide 022 For example, here’s a function called bounds that returns the lowest and highest elements of its parameter values at the same time.
slide 023 Sure enough, it returns a two-element tuple.
slide 024 And if we assign that tuple to a pair of variables, Python unpacks the two values and copies them into the variables in the right order.
slide 025 Functions sometimes use this technique to return a success or failure flag along with their actual result, which is only valid if the flag indicated success.
slide 026 Here, for example, read_if_available returns either True and a list of data values, or False and an empty list.
slide 027 Its caller can capture both values at once, then check the first to learn whether the second is meaningful or not.
slide 028 We’ll meet a better way to do this kind of thing in the lecture on testing.
slide 029 Multiple-valued assignment is also a quick way to swap variables’ values.
slide 030 Let’s initialize left and right to 0 and 10 respectively.
slide 031 And then assign left and right to right and left.
slide 032 Sure enough, when we’re done, Python has swapped their values.
slide 033 There’s no magic here: behind the scenes, Python is creating a temporary variable to hold onto one value while it copies the other.
slide 034 If we draw what’s in memory at the start, left refers to 0 and right refers to 10.
slide 035 Python creates a temporary variable (probably not actually named _tmp_, but that doesn’t matter)…
slide 036 …and copies left‘s pointer to 0 into it.
slide 037 It then copies right into left
slide 038 _tmp_ into right
slide 039 …and throws away the temporary variable, all behind the programmer’s back.
slide 040 Multi-valued assignment is also a quick and easy way to unpack the elements of lists.
slide 041 If colors holds the strings 'yellow', 'magenta', and 'lavender'
slide 042 …and we assign colors to a trio of variables called left, middle, and right
slide 043 …then sure enough, left has been assigned 'yellow', middle has been assigned 'magenta', and right has been assigned 'lavender'.
slide 044 This only works if the number of variables on the left to “catch” values is the same as the number of values in the list.
slide 045 Unpacking is often used to simplify loops.
slide 046 For example, suppose we have a list of pairs of numbers.
slide 047 We could add the values in each pair like this…
slide 048 …but it’s not particularly readable.
slide 049 Here’s a better way: the for loop gives us the pairs one by one, and when we assign each pair to the two variables low and high, Python automatically unpacks the pair’s values for us.
slide 050 We’ll use this technique a lot in the lectures that follow.
slide 051 To make life even easier, Python has a built-in function called enumerate that takes a sequence (i.e., a list, tuple, or string) as input, and produces (index, value) pairs—just right for looping.
slide 052 This bit of code uses enumerate to loop through our list of colors, printing each value and its index.
slide 053 The output is pretty much what you’d expect.
slide 054 And this is tidier and more efficient than the range(len(list)) idiom shown a few episodes ago.
slide 055

  1. Gorden Jemwa
    January 31st, 2011 at 23:25 | #1

    Very good overview of tuples in python. However, would it not be of value to also mention that while tuples are immutable, tuple elements that are mutable can still be changed?

  2. Shy Guy
    February 1st, 2011 at 05:45 | #2

    shouldn’t printing the tuple ‘least’ result in the display of the value -5 (rather than 5, as is shown in the slide)?

  1. No trackbacks yet.