question about Generator

Emile van Sebille emile at fenx.com
Sun Mar 3 11:48:36 EST 2002


"chongqing xiao" <cqxiao at charter.net> wrote in message
news:u84gjbo6v11dca at corp.supernews.com...
> Hi,
>
> Suppose if I have a generator (func) which will return [2,4,6,8]
>
> Is any way I can just get the first item (instead of using for x in
func()
> to get the first item)
> or stop before I get the last item in the Generator.

To get as many as you want, use next:

>>> def func():
...     i = 1
...     while 1:
...             yield i*2
...             i += 1
...
>>> a = func()
>>> a.next()
2
>>> a.next()
4

> Also, any comments on what the following code will do. (I don't have
2.2
> installed so I
> can't try it myself)

>>> def func():
...     i = 1
...     while i<5:
...             yield i*2
...             i+=1
...
>>> for x in func():
...     for y in func():
...             print x,y
...
2 2
2 4
[...]
8 4
8 6
8 8
>>>

HTH,

--

Emile van Sebille
emile at fenx.com

---------




More information about the Python-list mailing list