Generators are a special class of functions that simplify the task of writing iterators. They allow you to declare a function that behaves like an iterator, i.e., it can be used in a for loop to iterate over a sequence of values.
A generator function is defined like a normal function but uses the yield statement instead of return to yield values one at a time.
Example:
def simple_generator():
yield 1
yield 2
yield 3
# Using the generator
gen = simple_generator()
print(next(gen)) # Output: 1
print(next(gen)) # Output: 2
print(next(gen)) # Output: 3
# print(next(gen)) # Raises StopIteration
Generators are often used with loops to yield a series of values.
Example:
def countdown(n):
while n > 0:
yield n
n -= 1
# Using the generator
for number in countdown(5):
print(number)
Output:
5
4
3
2
1
Generator expressions provide a concise way to create generators. They are similar to list comprehensions but use parentheses instead of square brackets.
Example:
# List comprehension
squares_list = [x * x for x in range(10)]
# Generator expression
squares_gen = (x * x for x in range(10))
# Using the generator
for square in squares_gen:
print(square)
Output:
0
1
4
9
16
25
36
49
64
81