On Thu, 10 Nov 2005 21:46:37 -0800, [EMAIL PROTECTED] (Alex Martelli) wrote:
>[EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > >> > >>> list (x for x in xrange(20) if x<5 or iter([]).next()) >> > [0, 1, 2, 3, 4] >> > >> > Or a bit more readably: >> > >>> def stop(): raise StopIteration >> > ... >> > >>> list (x for x in xrange(20) if x<5 or stop()) >> > [0, 1, 2, 3, 4] >> > >> > IOW, your "when condition(x)" (IIUIC) can be spelled "if condition(x) or >> > stop()" >> If it is a single loop, takewhile/dropwhile is perfectly fine but as I >> mentioned in another post, it is nested and the condition needs >> surrounding scope so seperate function and StopIteration doesn't work >> as it breaks out of the whole thing expression. > >Can you give one example where this stop() function wouldn't work and >your hypothetical ``when'' would? I don't see how "it breaks out of the >whole thing expression" -- it terminates ONE for-clause (and what else >would your cherished ``when'' do?). > Well, it seems you do have to put them in the scopes of different generators, not just for-clauses, depending on the semantics you want e.g., >>> def stop(): raise StopIteration ... >>> list( ((x,y) for x in xrange(20) if x<5 or stop() for y in xrange(20) if >>> y<3 or stop())) [(0, 0), (0, 1), (0, 2)] >>> list( ((x,y) for x in xrange(20) if x<5 or stop() for y in (y for y in >>> xrange(20) if y<3 or stop()))) [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2), (3, 0), (3, 1), (3, 2), (4, 0), (4, 1), (4, 2)] Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list