lists and tuples

Steven Taschuk staschuk at telusplanet.net
Thu Jun 26 16:19:53 CEST 2003


Quoth Gerrit Holl:
> one of the things I have never understood in Python was why tuples
> exist. There is a FAQ entry about this:
  [...]
> > As a general guideline, use tuples like you would use structs in C
> > or records in Pascal, use lists like (variable length) arrays.
  [...]
> To make it more confusing, Guido wrote:
> > Tuples are for heterogeneous data, list are for homogeneous data.
> > Tuples are *not* read-only lists.
  [...]
> But this very FAQ entry was also written by Guido van Rossum.
> This FAQ entry does not use tuples for heterogeneous data.

It does, actually, though this use of the term "heterogeneous" can
be confusing.  (I know it confused me when I first read it.)

A couple tests:

Is seq[1:] conceptually the same kind of thing as seq itself?  If
so, seq should be a list; if not, a tuple.

Would it make sense to sort or use max on the sequence?  If so, a
list; if not, a tuple.

Examples:

A list of URLs:  If you chop off the first element, it's still a
list of URLs.  max(listofURLs) gives you the lexicographically
last of the URLs.

The time tuples used by the time module:  If you chop off the
first element, you don't have a time tuple anymore.  Sorting would
be useless, as would max(time.localtime()), both because the items
in the tuple are not conceptually comparable.

This has nothing to do with whether the elements of the sequence
are of heterogeneous types; it has to do with whether their
conceptual roles are heterogeneous.  The FAQ's example -- points
represented as (x, y) tuples -- is heterogeneous in this sense.
Note also that the sentence stating
    tuples : structs :: lists : arrays
(preserved above) reflects the same idea.

> What is the difference between immutable and read-only?

None.  (Well, "immutable" is slightly more precise.  It directly
states the essential point -- object cannot be changed -- without
reference to any notion of "read" and "write" operations.)

-- 
Steven Taschuk                                                   w_w
staschuk at telusplanet.net                                      ,-= U
                                                               1 1





More information about the Python-list mailing list