0
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 ?

3
  • Because, as it says generator is a function, not an iterator. It is a generator function, so it returns an iterator (a generator) Commented Aug 27, 2021 at 21:22
  • 1
    "generator" is a generator function which returns a generator (also usable as iterator) when called. Commented Aug 27, 2021 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, or to read the documentation (I admit the last part is hard to find). Commented Aug 27, 2021 at 23:21

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

Comments

1

Tru it with

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

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

Comments

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

2 Comments

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 :-)
No, please do say something :) I assume we're all here to learn, me included.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.