-1
def generator():
    yield 1
    yield 2
    yield 3
    yield 4
    
print(next(generator))
print(next(generator))
print(next(generator))
print(next(generator))

the error on vs is print(next(generator)) TypeError: 'function' object is not an iterator

i think the output should be 1 2 3 4

so why this error happend ?

  • Because, as it says `generator` is a function, not an iterator. It is a generator function, so it *returns* an iterator (a generator) – juanpa.arrivillaga Aug 27 '21 at 21:22
  • 1
    "generator" is a generator function which **returns** a generator (also usable as iterator) when called. – Michael Butscher Aug 27 '21 at 21:22
  • Welcome to Stack Overflow. The linked duplicate isn't the same question, but it will show you several proper examples of using a generator. Here's a quick hint, though: imagine if you had instead written `def generator(x):`. Where would you expect the value of `x` to come from? Another way you can understand how generators work is to try putting `python generator tutorial` [into a search engine](https://duckduckgo.com/?q=python+generator+tutorial), or to read the [documentation](https://docs.python.org/3/reference/expressions.html#examples) (I admit the last part is hard to find). – Karl Knechtel Aug 27 '21 at 23:21

3 Answers3

1

you defined 'generator' as a function that returns a generator you can call next on

def get_generator()
    yield 1
    yield 2

generator = get_generator()
first_value = next(generator)
print(first_value)
Raphael
  • 1,731
  • 2
  • 7
  • 23
1

Tru it with

generated = generator()
print(generated)
print(next(generated))

You need to call the method to start iterating it’s results

luk2302
  • 55,258
  • 23
  • 97
  • 137
1

This is the correct version:

def generator():
    yield 1
    yield 2
    yield 3
    yield 4

iterator = generator()

print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))

A function that contains yield statements is a generator. next, however, expects a generator iterator.

Generators create generator iterators.

For more information, look here for the difference between generators and generator iterators: https://docs.python.org/3/glossary.html#term-generator

Finomnis
  • 18,094
  • 1
  • 20
  • 27
  • 1
    Yes, better. Normally I don't say anything, people use these terms differently from those definitions a lot, it was just that you went so strongly and explicitly against it :-) – Kelly Bundy Aug 27 '21 at 23:22
  • No, please do say something :) I assume we're all here to learn, me included. – Finomnis Aug 27 '21 at 23:24