python-dev summary, July 16-31

Thomas Bellman bellman at lysator.liu.se
Thu Aug 9 13:47:53 EDT 2001


I wrote:

> I would always write this as

>    for x in [ 1, 2, 3 ]:
>	pass

I should probably explain this some more.

To me, a tuple isn't something that you iterate over.  A tuple is
a lightweight record.  The equivalent of a struct i C, but with
unnamed members.  The difference between lists and tuples isn't
really that tuples are read-only, but in how they are used.

A list typically holds a number of homogeneous elements.  All
elements are to be treated more or less the same.  The length
of the list is often not fixed.  The elements of the list might
be of different Python types or classes, 

The elements of a tuple, on the other hand, are heterogeneous.
They might be of the same Python type, but they don't mean the
same thing.  An example is the return value from time.gmtime():
the elements are all integers, but they have vastly different
meanings.  Coordinates is another example: the X, Y and Z
coordinates in a three-dimensional room have distinct meanings,
and it is seldom meaningful to iterate over the three values in a
single coordinate triple and doing a certain operation on each of
them.  In C you would implement a coordinate as

    struct coord_3d {
	double x,y,z;
    };

not as

    typedef double coord_3d[3];

Sure, there are examples when you want to iterate over the
elements in the struct/tuple, like when implementing matrix
multiplication, but those are special cases, not the norm for
how a tuple *should* be used.


-- 
Thomas Bellman,   Lysator Computer Club,   Linköping University,  Sweden
"I don't think [that word] means what you    !  bellman @ lysator.liu.se
 think it means."   -- The Princess Bride    !  Make Love -- Nicht Wahr!




More information about the Python-list mailing list