Mark As Completed Discussion

What are generators?

A generator is a function used to create iterator objects. it returns an object that can only be used with the for-in loop or next() methods.

But how does the compiler know that something is a generator? There's a special keyword yield for them. Whenever you see a yield keyword inside a function, we know that it is a generator.

Now let's see how a generator works. We can create a simple one:

PYTHON
1def simpleGenerator():
2    yield "a"
3    yield "b"
4    yield "c"
5    yield "d"

Now, if we call this function, it will return an iterator object.

PYTHON
1object = simpleGenerator()

If we try to access this object by using the print() function, it will generate the following output:

PYTHON
1print(object)

The output is:

PYTHON
1<generator object simpleGenerator at 0x0000017884AF2AC8>

We can only access this object using a for-in loop or the next() function.

PYTHON
1for value in simpleGenerator():
2    print(value)

The output will be our iterator object:

PYTHON
1a
2b
3c
4d

We can now use next() function, but it won't display the entire object. For example, look at the following code and its output:

PYTHON
1object = simpleGenerator()
2next(object)

The output will be:

PYTHON
1'a'

It has only shown the first yield value.

PYTHON
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment