Yield expressions are essentially generator comprehensions on juice. They allow us to write concise and readable code while still maintaining the power of generators. Let’s take a look at some examples:
# Creating a generator expression to generate even numbers from 0-99
even_gen = (i for i in range(100) if i % 2 == 0) # using the yield expression to create a generator that yields even numbers from 0-99
# Printing the first three elements of our generator
for num in even_gen: # iterating through the generator
print(num) # printing each element of the generator
In this example, we’re using a yield expression to generate an iterator that yields all the even numbers between 0 and 99. We then iterate over it using a for loop and print out the first three elements. Pretty cool right? But what if you want to take things up a notch?
# Generating prime numbers using yield expression
def is_prime(n):
# Checking if n is less than 2 (not prime)
if n < 2:
return False # If n is less than 2, it is not a prime number
# Iterating over all the numbers from 2 to sqrt(n)
for i in range(2, int(n**0.5)+1):
# If n is divisible by any number between 2 and sqrt(n), it's not prime
if n % i == 0:
return False # If n is divisible by any number between 2 and sqrt(n), it is not a prime number
# Otherwise, n must be a prime number!
return True # If n is not divisible by any number between 2 and sqrt(n), it is a prime number
# Generating all the prime numbers using yield expression
def generate_primes():
for num in range(2, 100):
if is_prime(num):
yield num # Yield the prime number if it passes the is_prime function
# Printing the first three prime numbers generated by the iterator
for prime in generate_primes():
print(prime) # Print the prime number generated by the iterator
In this example, we’re defining a function called `is_prime()` that takes an integer as input and returns True if it’s prime, False otherwise. We then use a for loop to iterate over all the numbers between 2 and sqrt(n) (inclusive), checking whether n is divisible by any of them using modulo operator (%). If we find a divisor, we know that n isn’t prime and return False immediately. Otherwise, if we reach the end of our loop without finding a divisor, we can safely assume that n must be a prime number!
We then use another yield expression to generate all the prime numbers between 2 and 100 using the `generate_primes()` function. This allows us to write concise code while still maintaining the power of generators. Pretty awesome right?
They may seem like just another feature at first glance, but they can really help streamline your code and make it more readable in certain situations. Give them a try !