
On Jan 29, 2013 9:26 AM, "Oscar Benjamin" oscar.j.benjamin@gmail.com wrote:
On 29 January 2013 11:51, yoav glazner yoavglazner@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?
Regards,
Zach Ware