Tuple comprehension

brueckd at tbye.com brueckd at tbye.com
Thu Apr 11 12:13:42 EDT 2002


On Thu, 11 Apr 2002, Magnus Lie Hetland wrote:

> It seems this has been brought up before, but I could only find two
> posts about it (about a year old). The question is: Could we have
> tuple comprehensions?
>
> The argument I saw used earlier was based on the author's
> preconceptions about tuples being primarily "records" and not
> "containers". The only defining quality I see to tuples as opposed to
> lists is that they are immutable. (Yes, I see the "recordness", but I
> don't think it's an argument against tuple comprehension.)

Maybe not directly, but it might argue against them simply because tuple
comprehensions wouldn't be used as much. They'd be useful when you're
using tuples as containers and not records, or when all the record members
are the same "type" to your application, e.g.:

coord = (x,y,z)
scaled = (f/2 for f in coord)

I use list comprehensions all the time, but I have trouble coming up with
too many cases where tuple comprehensions would be useful. Maybe I'm
missing a large set of potential uses?

> As far as I can see, the PEP on dict comprehension is still open... I
> think both dictionary comprehension and tuple comprehension seem like
> natural parallels to list comprehension. But then I would, wouldn't I?

I'd *love* to have dictionary comprehensions!

I guess the reason list and dictionary comprehensions make sense to me and
tuple comprehensions do not is because for lists and dictionaries they are
direct replacements for the initialize-to-empty-then-loop-to-populate
task, for which there is no tuple equivalent:

d = empty list or dict
for item in someInputSet:
    do something to item and add it to d

 -Dave






More information about the Python-list mailing list