List vs tuples

Donn Cave donn at u.washington.edu
Thu Apr 8 20:11:41 EDT 2004


In article <roy-BDDD71.17205008042004 at reader1.panix.com>,
 Roy Smith <roy at panix.com> wrote:
> "John Roth" <newsgroups at jhrothjr.com> wrote:
>> A list is a data structure that is intended to be used with 
>> homogenous members; that is, with members of the same type.
> 
> There's really nothing about a list which makes it more suitable for 
> homogeneous elements than a tuple.  It's true that people do tend to 
> think tuple when they want a mixed collection of objects, but there's 
> nothing in the language semantics which makes that so.
> 
> I've written lots of code which parses data files.  If you've got a 
> sequence of arbitrary type objects, the easiest way to process them is 
> often to read them sequentially and append them to a list.  I don't see 
> anything wrong with that.  For example, I once had to write some code 
> which parsed SQL statements that looked something like:
> 
> insert into foo values (1, 2, 'foo', 3.14, 'bar', 4, 5, 'baz', ...);
> 
> There were a total of about 30 items of mixed type (strings, integers, 
> and floats) in the ()'s. 
> 
> One of the really nice things about Python (vs. C++ or Java) is that 
> you're not bound by the tyranny of static typing.  This is a perfect 
> example of how this makes life so simple.

Oh no, here we go again.

In the hope that we can all get along, here's how
both of these arguments can be true.  And I'm sure
Guido would agree if he were reading this, unless
he was in an unusually obtuse frame of mind.

Lists are indeed homogeneous by nature, but that
doesn't mean that each element has the same type
as the next.  It means that any slice of the list
has the same "type" as any other slice.

When we are dealing with a record type, an ordered
collection of items where an item's meaning is
determined by its position, this obviously should
be a tuple.  For example, the tm struct returned
from time.localtime():  each member is an integer,
but it's not homogeneous in the list sense - the
only valid slice of a tm value is [:], any other
slice is not a tm value, its type is different
even if it is still a tuple.

When we are dealing with a regular list, its type
is the same before and after you append() a new
element.  That doesn't mean that the new element
is the same type as its predecessor, it just means
that the list isn't itself a new type now that it
has that last element.

   Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list