Generator Question
Chris Angelico
rosuav at gmail.com
Thu Dec 22 01:08:12 EST 2011
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
More information about the Python-list
mailing list