0

I wrote the following into the Python interpreter today:

>>> def test():
...     for c in ['a', 'b', 'c', 'd']: yield c
...
>>> a = test()
>>> a
<generator object test at 0x2556a00>
>>> a.next()
'a'
>>> a.next()
'b'

This was surprising to me. Shouldn't test return (or yield) one of the elements in my list, not a generator which yields them?

A second function which uses "return" behaves as expected:

>>> def test2():
...     for i in ['a', 'b', 'c', 'd']: return i
...
>>> b = test2()
>>> b
'a'
>>> b
'a'

Why is this so? Where in the documentation describes this behaviour?

Eric Dand
  • 1,106
  • 13
  • 37

1 Answers1

-4

Because your yield is nested in your for loop, all your values will be added to the generator expression. Generators are basically equivalent to iterators except, iterators retain the values unless deleted whereas generators generate the values once on the fly. The next method of the generator is implicitly called by the way when used in a for loop rather than a generator.

In addition, you must remember that the return keyword returns one and only on value as does yield. The function returns one generator object with yield that is ready to generate all the supplied values. A standard return statement though returns a value and exits the function so that the other values aren't returned.

Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70
  • 3
    -100 This is complete nonsense. An iterator is just an object with a `__next__()` method. Iterators do **not** "retain the values unless deleted", whatever that means. And a `yield` statement does not "return a generator object", it turns the function into a generator function. – augurar Mar 03 '15 at 22:45
  • I don't know what you mean by the function turning into something else. – Malik Brahimi Mar 03 '15 at 22:55
  • Any function definition containing a `yield` statement is considered by the interpreter to be a generator function. It is not the `yield` statement itself that returns a generator object. – augurar Mar 03 '15 at 22:57
  • Yes, exactly, the function returns the generator, the yield is a directive to do so. That's what I meant by yield. – Malik Brahimi Mar 03 '15 at 22:59