Lists and Tuples

Skip Montanaro skip at pobox.com
Fri Dec 5 12:10:34 EST 2003


(Probably more response than you wanted.  I kind of got carried away...)

    >> I've spent most of the day playing around with lists and tuples to
    >> get a really good grasp on what you can do with them. I am still left
    >> with a question and that is, when should you choose a list or a
    >> tuple?

Generally, choose between tuples and lists based upon your data.  In
situations where you have a small, fixed collection of objects of possibly
differing types, use a tuple.  In situations where have a collection of
objects of uniform type which might grow or shrink, use a list.  For
example, an address might best be represented as a tuple:

    itcs = ("2020 Ridge Avenue", "Evanston", "IL", "60201")
    caffe_lena = ("47 Phila Street", "Saratoga Springs", "NY", "12866")

Though all elements are actually strings, they are conceptually different
types.  It probably makes no sense to define itcs as

    itcs = ("2020 Ridge Avenue", "60201", "IL", "Evanston")

If you are reading test scores from a file, you'd likely accumulate them
into a list:

    scores = []
    for line in file("foo"):
        scores.append(float(line.strip()))

then operate on them as a group, possibly normalized to the list's length:

    nscores = len(scores)
    mean = sum(scores)/nscores
    variance = sum([(n-mean)**2 for n in scores])/nscores
    print "Mean:", mean
    print "Variance:", variance

Unlike tuples, it's often perfectly reasonable to reorder lists without any
loss of meaning:

    scores.sort()
    print "Min:", scores[0]
    print "Max:", scores[-1]
    print "Median:", scores[nscores/2:nscores/2+1]

Think of lists as arrays and tuples as Pascal records or C structs and
you'll probably choose correctly most of the time.

If you want to associate methods with your tuples (similarly for lists), you
should probably define a class instead:

    import latlong

    class Address:
        def __init__(self, street, city, state, zip):
            self.street = street
            self.city = city
            self.state = state
            self.zip = zip

        def distance(self, other):
            return latlong.cdistance("%s, %s" % (self.city, self.state),
                                     "%s, %s" % (other.city, other.state))

    itcs = Address("2020 Ridge Avenue", "Evanston", "IL", "60201")
    caffe_lena = Address("47 Phila Street", "Saratoga Springs", "NY", "12866")
    print itcs.distance(caffe_lena), "miles"

For the curious, when run, the above prints:

    961.976657911 miles

Looks like I won't be attending a concert at Caffe Lena tonight.

(latlong is a module I wrote for use in the Mojam and Musi-Cal websites but
never released publically.)

Skip






More information about the Python-list mailing list