[Python-ideas] Accessing the result of comprehension's expression from the conditional

Georg Brandl g.brandl at gmx.net
Sun Jun 21 11:46:40 CEST 2009


Lie Ryan schrieb:

>>> I hate it. It mixes map/filter style and comprehension style; and the
>>> fact it does so in a single line only makes it worse. Not that it would
>>> be any better in two lines.
>> 
>> Taking this further, using only map/filter style like this
>> 
>> filter(pred, map(f, seq))
>> 
>> takes two steps. Why is it so bad that doing it in a listcomp
>> 
>> (el for el in (f(y) for y in seq) if el > 2)
>> 
>> takes two steps as well?
>> 
>> Georg
>> 
> 
> Comprehension, by its nature, is map+filter in a single expression.

Let's stick with "+" for function composition.  Then comprehension is,
as you say, ``map + filter`` (map after filter).  It is *not*
``filter + map`` (filter after map), which is what would be needed in
the case discussed in this thread.  In the functional waym you can of
course combine map and filter in the order you like.

> Nested comprehension is (map+filter)+(map+filter).

Yes, and in this case, we use it as ``(id+filter) + (map+id)``, which is
the easiest way to build a ``filter + map`` with the ``map + filter``
building block.

> Mixing the two styles is ugly since it means you have to think in two
> separate (though related) paradigms.

I mentally translate map and filter into comprehensions anyway (or maybe
rather both translate into the same more abstract thing), so I don't see
it as ugly.

Georg




More information about the Python-ideas mailing list