The Yield statement

inhahe inhahe at gmail.com
Sun Jul 6 03:04:02 EDT 2008


"Alex Bryan" <alexnbryan at gmail.com> wrote in message 
news:mailman.1009.1214865088.1044.python-list at python.org...
> Okay, so i don't really understand the Yield thing and i know it is 
> useful. I've read a few things about it but it is all programming  jargon 
> and so basically it is hard for me to understand. So can anyone  give me a 
> description or link me to a site that has a good definition  and/or 
> examples of it? If you could I would really appreciate it.

Really short answer:

def f():
  yield 1
  yield 2
  yield 3

for x in f(): print x,
# should print 1 2 3

def f():
  for x in xrange(10):
    yield x

for x in f(): print x,
# should print 0 1 2 3 4 5 6 7 8 9

note that this won't work;
def f():
  for x in xrange(10):
    for y in xrange(10):
      yield (x,y)

yield just doesn't work right with multiple levels of loops. i had to 
discover that the hard way.






More information about the Python-list mailing list