Tuple comprehension

Quinn Dunkan quinn at bolivar.ugcs.caltech.edu
Sun May 26 14:07:42 EDT 2002


On Fri, 12 Apr 2002 08:20:36 -0700 (PDT), brueckd at tbye.com <brueckd at tbye.com>
wrote:
>On Thu, 11 Apr 2002, David Eppstein wrote:
>
>> In article <slrnabchgs.c8l.mlh at vier.idi.ntnu.no>,
>>  mlh at vier.idi.ntnu.no (Magnus Lie Hetland) wrote:
>>
>> > I think the only _real_ reason to have tuples at all is that they are
>> > immutable (and therefore usable as dictionary keys). And a slight
>> > efficiency advantage over lists, maybe...
>>
>> I'm guessing (without looking at the source) that tuples use less memory
>> because they don't need the extra room for growth that lists do.
>> But my mental model of them is just "immutable list".
>
>Yes, this is where the difference in opinion lies: as immutable lists,
>tuple comprehensions can make sense. I like the mental model of tuples
>put forth by the Python tutorial:
>
>[5.3] "Tuples have many uses, e.g. (x, y) coordinate pairs, employee
>records from a database, etc."
>
>The implication is that tuples group bits of often dissimilar but related
>information that, grouped together, represent a unique entity - sort of a
>poor man's object instance.

This is how I think of them too.  One test is that if you create them with
literal constructors (which you must, since (without tuple constructors) you
have no choice) and destruct them with pattern patching (as in 'x, y = coords')
and their length is part of their 'type', then they are tuples.  

If you create them piecemeal (by appending) and tend to index them or iterate
over them (this including mapping), and they can be any length, then they are
lists.

I suspect I think of things in these terms because of previous languages where
the difference is part of the language (e.g. lists must be homogenous and
tuples cannot be indexed).

Where one person might write:

def move(coord, vector):
    return tuple(map(operator.add, coord, vector))

I might write:

def move((x1, y1), (x2, y2)):
    return (x1 + x2, y1 + y2)

Of course, the second version is less generic since it only works for pairs,
but if I had a system with n-dimensionsal coords maybe I'd use lists since
they can be various lengths.  This would be a hint to think of additional
cases such as "what happens when you move a 3d point by a 2d vector?".



More information about the Python-list mailing list