Like list comprehensions, generator expressions can also include conditional statements to filter the iterable items. Here's an example of a generator expression with a conditional:
# A generator expression that yields the square of each even numbersquares_generator = (num**2 for num in range(10) if num % 2 == 0)# Iterate over the generator and print each resultfor square in squares_generator: print(square) |
In this example, we use a generator expression to create a generator object that yields the square of each even number in the range of 0 to 9. The conditional statement if num % 2 == 0 filters the iterable to only include even numbers, and the expression num**2 yields the square of each even number. We then use a for loop to iterate over the generator and print each square.
Note that the conditional statement is included after the for loop statement in the generator expression syntax, just like it is in a list comprehension. If you need to include multiple conditions, you can use the and and or operators to combine them. For example:
# A generator expression that yields the square of each even number between 2 and 8squares_generator = (num**2 for num in range(10) if num % 2 == 0 and num >= 2 and num <= 8)# Iterate over the generator and print each resultfor square in squares_generator: print(square) |
In this example, we use a generator expression to create a generator object that yields the square of each even number between 2 and 8. The conditional statement if num % 2 == 0 and num >= 2 and num <= 8 filters the iterable to only include even numbers between 2 and 8, and the expression num**2 yields the square of each even number. We then use a for loop to iterate over the generator and print each square.