[Tutor] Creating a complex python object

Jeff Shannon jeff at ccvcorp.com
Fri Aug 13 20:13:19 CEST 2004


Chad Crabtree wrote:
>  >In the mean time I'll keep lurking on this list, there's still a
> lot 
> to python that baffles me (like just what is the difference between a
> tuple and a list?  :-)   ).
> 
> I thought I would answer the tuple list thing.  I did not understand
> why 
> have tuple's until I learned that tuples being immutable are faster
> and 
> easier on memory.

Actually, speed and memory considerations are only incidental.

One of the most important reasons that Python has both (mutable) lists 
and (immutable) tuples is because dictionaries don't work with mutable 
keys.  If you stuck something into a dictionary that was keyed on a 
list, and then that list changed, you'd never be able to get that 
dictionary value back.  But dictionaries are an important part of 
Python (many internal data structures are effectively dictionaries, 
among other things), and it's very valuable to be able to use a group 
  of items as keys -- for example, a dictionary showing grid locations 
is much cleaner if you can key off of (x, y), rather than having a 
dictionary at x that has another dictionary that's keyed off of y.

So, dictionaries are the reason that we have tuples.  But once we 
*have* them, they tend to grow other differences...

The common usage, now, is that lists usually contain a sequence of 
similar things, whereas tuples are usually more like a record, 
grouping together dissimilar things that are conceptually related. 
Thus, for example, in the date-time tuple returned by time.gmtime() 
each position within the tuple represents a different thing.  In 
contrast, each position in a list represents a different instance, but 
all of the contents are the same type of thing.  This distinction is 
just convention, of course, and there's nothing forcing you to follow 
it, but you'll find that just about every standard library module (and 
most other code, as well) will follow this guideline.

Jeff Shannon
Technician/Programmer
Credit International



More information about the Tutor mailing list