Welcome to the Yield Statement lesson! In this comprehensive guide, we'll delve into one of Python's unique features – the yield statement. This powerful tool will help you create iterable objects like lists and generators. Let's get started!
The yield statement is a keyword in Python that allows functions to act like iterators, producing values one at a time. When a yield function is called, it doesn't return a value but suspends itself, allowing the code to continue executing elsewhere.
Using the yield statement can be beneficial for several reasons:
To create a generator, you simply need to use the yield keyword within a function. Here's a simple example:
def my_generator():
yield 1
yield 2
yield 3You can iterate over the generator using the next() function:
generator = my_generator()
print(next(generator)) # Output: 1
print(next(generator)) # Output: 2
print(next(generator)) # Output: 3Notice that the function doesn't end when we call next(). Instead, the function returns a generator object, which we can call again and again to get the next yielded value.
While list comprehensions are a great way to create lists in Python, they can be memory-intensive for large datasets. Generators, on the other hand, offer a more memory-efficient solution:
def my_generator(n):
for i in range(n):
yield i * 2
my_list = list(my_generator(5))
print(my_list) # Output: [0, 2, 4, 6, 8]In this example, the generator creates the list on-the-fly, only storing the current value in memory while iterating.
You can also create a generator using a syntax similar to list comprehensions, enclosed by parentheses instead of square brackets:
my_generator = (i * 2 for i in range(5))
print(next(my_generator)) # Output: 0
print(next(my_generator)) # Output: 2You can use the yield statement within loops to create custom iterators:
def my_custom_iterator(n):
for i in range(n):
yield i * 2
yield i * 3
my_iterator = my_custom_iterator(5)
print(next(my_iterator)) # Output: 0
print(next(my_iterator)) # Output: 0
print(next(my_iterator)) # Output: 6
print(next(my_iterator)) # Output: 9The yield from statement allows you to delegate the iteration process to another generator:
def my_composite_generator():
for i in range(5):
yield i
yield from my_custom_iterator(5)
my_generator = my_composite_generator()
print(next(my_generator)) # Output: 0
print(next(my_generator)) # Output: 1
print(next(my_generator)) # Output: 2
print(next(my_generator)) # Output: 3
print(next(my_generator)) # Output: 0
print(next(my_generator)) # Output: 2
print(next(my_generator)) # Output: 4What is a generator in Python?
What is the purpose of the `yield` keyword in Python?
What is the main advantage of using generators over lists?