List vs tuples

Isaac To kkto at csis.hku.hk
Fri Apr 9 05:46:18 EDT 2004


>>>>> "John" == John Roth <newsgroups at jhrothjr.com> writes:

    John> It's a common question. A list is a data structure that is
    John> intended to be used with homogenous members; that is, with members
    John> of the same type.

I feel you argument very strange.  Even that it might be the original
intention, I see nothing in the language that support your argument.

In particular, nothing says that tuples cannot be used (or is troublesome to
use) when members are of the same type.  And nothing says that lists cannot
be used (or is troublesome to use) when members are of different types.

    John> You've probably used tuples without realizing it. For example, the
    John> following idiom involves a tuple:

    John> hours, minute, second = getTime()

    John> where

    John> def getTime(.....)  #some calc return hour, minute, second

    John> While it looks like return is returning multiple objects, it
    John> actually isn't. It's returning one object: a tuple of three
    John> elements which is then being unpacked on the receiving end.

If getTime() give you a list instead, then [hours, minute, second] =
getTime() would still give you the hours, minute and second variables
assigned.

    John> You could call the same routine this way as well:

    John> result = getTime()

    John> and result would be a tuple of three elements.

And if getTime() give you a list of course result would be a list instead.
Nothing magic.

    John> Another way of thinking about it is that you would use a tuple the
    John> same way you would use a struct in a language like C, if you
    John> didn't want to go to the trouble of creating a full-fledged object
    John> for it.

And you can use a list here as well.  Indeed, if you want to emulate C
struct, you probably will use list instead of tuples, since in C, structs
are mutable.

Regards,
Isaac.



More information about the Python-list mailing list