Tuple comprehension

Sean 'Shaleh' Perry shalehperry at attbi.com
Thu Apr 11 11:40:28 EDT 2002


> 
> 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
> 

since tuples are immutable there is no
initialize-to-empty-then-loop-to-populate idiom, you are correct.  Because of
this when a tuple would work we have to use lists.  Numerous times while coding
I have started using a tuple and had to fall back to lists because I eventually
needed a way to give all of the values in my list a value based on a function.

I personally like tuples because they say "this list is immutable, it won't
grow or shrink and try not to touch its contents".  Just like using 'const' and
'private' in other languages.

If there was a way to create a tuple whose contents were programmatically
created and avoid the list -> tuple conversion I suspect tuples would get more
use.





More information about the Python-list mailing list