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

Oscar Benjamin oscar.j.benjamin at gmail.com
Tue Jan 29 16:25:40 CET 2013


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.


Oscar



More information about the Python-ideas mailing list