[Python-ideas] Generator syntax hooks?
Stefan Behnel
stefan_ml at behnel.de
Tue Aug 8 03:48:17 EDT 2017
Soni L. schrieb am 08.08.2017 um 01:56:
> On 2017-08-07 08:35 PM, Steven D'Aprano wrote:
>> Hi Soni, and welcome!
>>
>> On Mon, Aug 07, 2017 at 04:30:05PM -0300, Soni L. wrote:
>>
>>> What if, (x for x in integers if 1000 <= x < 1000000), was syntax sugar
>>> for (x for x in range(1000, 1000000))?
>> If you want the integers from 1000 to 1000000, use:
>>
>> range(1000, 1000000)
>>
>> Don't waste your time slowing down the code with an unnecessary and
>> pointless wrapper that does nothing but pass every value on unchanged:
>>
>> (x for x in range(1000, 1000000)) # waste of time and effort
>
> Actually, those have different semantics!
>
>>>> x = range(1, 10)
>>>> list(x)
> [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>> list(x)
> [1, 2, 3, 4, 5, 6, 7, 8, 9]
>
>>>> x = (x for x in range(1, 10))
>>>> list(x)
> [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>> list(x)
> []
In that case, use iter(range(1000, 1000000)).
range() creates an iterable, which is iterable more than once.
iter(range()) creates an iterator from that iterable, which has the
semantics that you apparently wanted.
Stefan
More information about the Python-ideas
mailing list