[Python-ideas] Tuple Comprehensions

Karthick Sankarachary karthick.sankarachary at gmail.com
Tue Oct 11 01:36:06 CEST 2011


Hi, All,

As Masklinn pointed out, the issue is that there's no concise way to
accumulate or compress an iterable without resorting to the use of the
reduce() function.

To answer Greg's point, it's not like list comprehensions cover all the
cases allowed by the concept of mapping. There are cases, such as when the
construction rule is too complicated, where comprehensions cannot be
applied. Given that, why not explore the idea of if and how we can make
(simple) reductions more readable.

To me, the tricky part was resolving the ambiguity between a map and reduce
expression in the comprehension. Given that the first argument to the
reduce() function is the accumulated value, which is something that the
map() function doesn't need, I felt that we could use that to make the
distinction between the two in the comprehension. In particular, if the
expression in the comprehension refers to the accumulated value (through the
"_" variable), then it could treat it as a reduction as opposed to a
mapping.

Here's another example to illustrate the desired behavior, which basically
adds a list of numbers (without resorting to the use of a reduce()):

>>> numbers=[1,2,3,4,5]
>>> [_+number for number in numbers]
15

Just to clarify, we're just talking about some syntactic sugar here, nothing
more, nothing less.

Best Regards,
Karthick Sankarachary


On Mon, Oct 10, 2011 at 2:26 PM, Greg Ewing <greg.ewing at canterbury.ac.nz>wrote:

> Karthick Sankarachary wrote:
>
>> 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.
>>
>
> There was a big discussion a while back about a syntax for
> reduction operations. The conclusion reached was that the
> concept of reduction has so many degrees of freedom that,
> beyond the very simple cases covered by the reduce() function,
> nothing is clearer than simply writing out the loop explicitly.
>
> --
> Greg
>
> ______________________________**_________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/**mailman/listinfo/python-ideas<http://mail.python.org/mailman/listinfo/python-ideas>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20111010/ffcfa116/attachment.html>


More information about the Python-ideas mailing list