[Python-ideas] while conditional in list comprehension ??

Ian Cordasco graffatcolmingov at gmail.com
Mon Jan 28 15:38:58 CET 2013


On Mon, Jan 28, 2013 at 8:59 AM, Oscar Benjamin
<oscar.j.benjamin at gmail.com> wrote:
> On 28 January 2013 13:56, Chris Angelico <rosuav at gmail.com> wrote:
>> On Tue, Jan 29, 2013 at 12:33 AM, Wolfgang Maier
>> <wolfgang.maier at biologie.uni-freiburg.de> wrote:
>>> Why not extend this filtering by allowing a while statement in addition to
>>> if, as in:
>>>
>>> [n for n in range(1,1000) while n < 400]
>>
>> The time machine strikes again! Check out itertools.takewhile - it can
>> do pretty much that:
>>
>> import itertools
>> [n for n in itertools.takewhile(lambda n: n<400, range(1,1000))]
>>
>> It's not quite list comp notation, but it works.
>>
>>>>> [n for n in itertools.takewhile(lambda n: n<40, range(1,100))]
>> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
>> 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
>> 37, 38, 39]
>
> The while clause is a lot clearer/nicer than takewhile/lambda.
> Presumably it would be more efficient as well.

The while syntax definitely reads better, and I would guess that dis
could clarify how much more efficient using `if n < 400` would be
compared to the lambda. Then again this is a rather uncommon situation
and it could be handled with the if syntax. Also, if we recall the zen
of python "There should be one-- and preferably only one --obvious way
to do it." which is argument enough against the `while` syntax.



More information about the Python-ideas mailing list