
Oscar Benjamin <oscar.j.benjamin@...> writes:
On 29 January 2013 11:51, yoav glazner <yoavglazner@...> 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
list(i for i in range(100) if i<50 or stop()) Really (!) nice (and 2x as fast as using itertools.takewhile())!
With the somewhat simpler (suggested earlier by Shane)
def stop(): raise StopIteration
this should become part of the python cookbook!!
Thanks a real lot for working this out, Wolfgang