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

Joao S. O. Bueno jsbueno at python.org.br
Tue Jan 29 17:01:28 CET 2013


On 29 January 2013 13:34, Zachary Ware <zachary.ware+pyideas at gmail.com> wrote:
>
> On Jan 29, 2013 9:26 AM, "Oscar Benjamin" <oscar.j.benjamin at gmail.com>
> wrote:
>>
>> On 29 January 2013 11:51, yoav glazner <yoavglazner at gmail.com> wrote:
>> > Here is very similar version that works (tested on python27)
>> >>>> def stop():
>> > next(iter([]))
>> >
>> >>>> list((i if i<50 else stop()) for i in range(100))
>> > [0, 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,
>> > 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]
>>
>> That's a great idea. You could also do:
>> >>> list(i for i in range(100) if i<50 or stop())
>>
>> It's a shame it doesn't work for list/set/dict comprehensions, though.
>>
>
> I know I'm showing my ignorance here, but how are list/dict/set
> comprehensions and generator expressions implemented differently that one's
> for loop will catch a StopIteration and the others won't? Would it make
> sense to reimplement list/dict/set comprehensions as an equivalent generator
> expression passed to the appropriate constructor, and thereby allow the
> StopIteration trick to work for each of them as well?
>

That is because whil list/set/dict constructors are sort of "self contained",
a generator expression - they will expect the StopIteration to be raised by the
iterator in the "for" part os the expression.

The generator expression, on the other hand, is an iterator in itself, and it is
expected to raise a StopIteration sometime.

The code put aroundit to actually execute it will catch the StopIteration -
and it won't care wether it was raised by the for iterator or by any other
expression in the iterator.

I mean - when you do list(bla for bla in blargh) the generator is
exausted inside the "list"
call - and this generator exaustion is signaled by the StopIteration
exception in both cases.


> Regards,
>
> Zach Ware
>
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>



More information about the Python-ideas mailing list