[Python-ideas] Tuple Comprehensions

Terry Reedy tjreedy at udel.edu
Mon Oct 10 00:19:04 CEST 2011

On 10/9/2011 4:57 PM, Karthick Sankarachary wrote:

> There are a couple of constraints in the above definition that I feel
> could be overcome. For one thing, list comprehensions don't let you
> create immutable sequences (such as a tuple) by design.

To create an 'immutable' collection, one has to have all the items 
present from the beginning, along with their count. If the items are 
generated one at a time, they must be collected in a temporary mutable 
internal structure. So '(' comprehension ')' syntax like

>>>>  (weapon.strip()  for  weapon  in  freshfruit)

was used to define and call an anonymous generator function, thus 
resulting in a generator. This is more flexible than making the result a 
tuple and in line with the Python 3 shift of emphasis toward iterators.

> In the first tuple comprehension, we create a true tuple with multiple
> items. This might a tad more efficient, not to mention less verbose,
> than applying the "tuple" function on top of a list comprehension.

tuple(weapon.strip()  for  weapon  in  freshfruit) does little more than 
would have to be done anyway to produce a tuple.

It is also a fairly rare need. A comprehension by its nature produces a 
homogeneous sequence as all items are produced from the same expression. 
In real use, tuples tend to be short and often heterogeneous.

Terry Jan Reedy

More information about the Python-ideas mailing list