next() on an exhausted generator will lead to StopIteration exception.yield keyword at least once in its definition. They may contain return keyword with no arguments. Just like any other function, there is an implicit return at the end of the definition.# Example
def gen123():
yield 1
yield 2
yield 3
>>> g = gen123() # g is now a generator object (an iterator)
>>> next(g) # 1
>>> next(g) # 2
>>> next(g) # 3
# Subsequent calls will return in StopIteration exception
# We can also use generator objects in for loops
for v in gen123():
print(v)
We can also use generator objects in for loops - when we implicitly call next() on a generator object, we will get a StopIteration exception when all the values have been yielded - this does not happen when the generator object is used in a for loop, as the for loop handles the exception.
even_integers = (n for n in range(10) if n%2 == 0)
for num in even_integers:
print(num)
We can also use generator expressions directly in for loops:
for n in (i for i in range(10) if i%2==0):
print(n)
Generator Expressions are another way to create generator objects. They are identical to list comprehensions in terms of syntax - we use parenthesis instead of brackets, and the generator expression evaluates to a generator object rather than a list.
#generator expression - example 1
(item.upper() for item in collection)
#generator expression - example 2
even_integers = (n for n in range(10) if n%2 ==0)
>>>list(even_integers) #[0,2,4,6,8]