[ x for x in xrange(10) when p(x) ]

bonono at gmail.com bonono at gmail.com
Fri Nov 11 22:24:49 EST 2005


Bengt Richter wrote:
> 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)]
>
thanks. it works and I have explained in another post why I initially
confused and thought it didn't work. stand corrected.

However, I found something interesting which I don't quite understand :

list((x for x in [1,2,3] if x<2 or stop())) works

but

a = [ x for x in [1,2,3] if x <2 or stop() ] doesn't.




More information about the Python-list mailing list