[Python-ideas] Tuple Comprehensions

Karthick Sankarachary karthick.sankarachary at gmail.com
Sun Oct 9 22:57:16 CEST 2011


Hello Python Ideas,

To quote the tutorial, "List comprehensions provide a concise way to create
lists without resorting to use of map(), filter() and/or lambda.".

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. For another, it does not
provide a concise alternative to reduce() function.

To address both of the above, I'd like to introduce tuple comprehensions,
which would work like so:

>>> freshfruit = ['  banana', '  loganberry ', 'passion fruit  ']
>>> (weapon.strip() for weapon in freshfruit)
('banana', 'loganberry', 'passion fruit')
>>> import operator
>>> (operator.concat(_, weapon.strip()) for weapon in freshfruit)
'bananaloganberrypassion fruit'

As you can see, we use parenthesis instead of square brackets around the
comprehension.

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.

In the second tuple comprehension, we use a reduce() function (specifically
operator.concat) to concatenate all of the fruit names. In particular, we
use the "_" variable (for lack of a better name) to track the running
outcome of the reduce() function.

Best Regards,
Karthick Sankarachary
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20111009/5467a44f/attachment.html>


More information about the Python-ideas mailing list