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:
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.
1object = simpleGenerator()
If we try to access this object by using the print()
function, it will generate the following output:
1print(object)
The output is:
1<generator object simpleGenerator at 0x0000017884AF2AC8>
We can only access this object using a for-in
loop or the next()
function.
1for value in simpleGenerator():
2 print(value)
The output will be our iterator object:
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:
1object = simpleGenerator()
2next(object)
The output will be:
1'a'
It has only shown the first yield value.
xxxxxxxxxx
def simpleGenerator():
yield "a"
yield "b"
yield "c"
yield "d"
object = simpleGenerator()
print(object)
for value in simpleGenerator():
print(value)