[Python-ideas] Integrate some itertools into the Python syntax

João Bernardo jbvsmo at gmail.com
Wed Mar 23 20:08:38 EDT 2016


João Bernardo

On Wed, Mar 23, 2016 at 7:18 PM, Michael Selik <mike at selik.org> wrote:

>
>>> [x for x in range(10) while x < 5]      # takewhile
>>> [x for x in range(10) not while x < 5]  # dropwhile
>>> [x for x in range(10) from x >= 5]      # forward thinking dropwhile
>>>
>>> I believe this is almost plain english without creating new keywords.
>>>
>>
>> They read well, except for the square brackets which to me imply
>> consuming the entire iterator. Itertools takewhile will early exit,
>> possibly leaving some values on the iterator. If these do consume the
>> entire iterator, what's the difference with the ``if`` clause in a
>> comprehension?
>>
>>
>> But isn't that their purpose? Not consuming. I think that would be easy
>> to learn. +1 on this proposal.
>>
>> This could also prove useful to avoid for-else. :-)
>>
>
> After the execution of the list comprehension using "while" if the
> condition triggered halfway, would there be anything left in the original
> iterator? If it was a generator expression, we'd say "Yes" immediately.
> As a list comprehension, I'm not sure.
>


Dropwhile alone would consume the entire iterator for obvious reasons.
Takewhile will stop when necessary, otherwise why implement it?

You could nest them and still be readable:

[x for x in range(10) from x > 3 while x < 7]

Still quite readable. If this were an iterator like "foo = iter(range(10))",
there will be items left in the end.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160323/b71ef2c1/attachment.html>


More information about the Python-ideas mailing list