Generator Question
Chris Angelico
rosuav at gmail.com
Thu Dec 22 01:08:12 EST 2011
More information about the Python-list mailing list
Thu Dec 22 01:08:12 EST 2011
- Previous message (by thread): Generator Question
- Next message (by thread): Generator Question
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On Thu, Dec 22, 2011 at 4:45 PM, GZ <zyzhu2000 at gmail.com> wrote: > def h(): > if condition=true: > #I would like to return an itereator with zero length > else: > for ...: yield x Easy. Just 'return' in the conditional. >>> def h(): if condition: return for i in range(4): yield i >>> condition=False >>> h() <generator object h at 0x01913E68> >>> for i in h(): print(i) 0 1 2 3 >>> condition=True >>> h() <generator object h at 0x01079E40> >>> for i in h(): print(i) >>> A generator object is returned since the function contains a 'yield'. On one of the branches, nothing will ever be yielded and StopIteration will be raised immediately. You could probably also raise StopIteration directly, but it's not necessary. ChrisA
- Previous message (by thread): Generator Question
- Next message (by thread): Generator Question
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list