[Tutor] Workaround for limitation in xrange()?

Alan Gauld alan.gauld at btinternet.com
Tue Oct 10 22:45:47 CEST 2006

"Dick Moores" <rdm at rcblue.com> wrote in message 
news: at rcblue.com...
> Encapsulate the while loop in a generator:
> def count(limit):
>   n=0
>   while n<limit:
>     yield n
>     n += 1
> All 3 are essentially the same, aren't they. Which makes me feel 
> even
> dumber, because I don't understand any of them. I've consulted 3
> books, and still don't understand the use of yield.

Think of yield as being the same as return except that next time
you "call the function" all the state is preserved and it picks up 
after the yield.

So first time you call count above it returns 0
next time you call it it executes the n+= 1 and goes round the loop
again until it hits yield when it returns 1.
next time you call it executes y+=1 again, but because the state has
been remembered n goes to 2 and yield returns that
and so on until you reach n = limit at which point it just
exits with StopIteration.  Here is a short example:

>>> def y(n):
...   j = 0
...   while j < n:
...     yield j
...     j += 1
>>> try:
...    x = y(7)
...    for n in range(20):
...      print x.next()
... except StopIteration:
...   print 'Reached the end'
Reached the end

Does that help?

Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list