How to Create a Python Comprehension Generator?

Estimated read time 1 min read

To create a Python comprehension generator, you can use a generator expression inside a pair of parentheses. Here’s an example:

my_list = [1, 2, 3, 4, 5]

my_gen = (x ** 2 for x in my_list if x % 2 == 0)

for val in my_gen:
    print(val)

In this example, we define a list my_list and use a generator expression to create a new generator my_gen. The generator expression squares each even number in my_list.

We then use a for loop to iterate over the values generated by my_gen and print them to the console.

The resulting output will be:

4
16

This example demonstrates how to use a generator comprehension to create a sequence of values that are generated on the fly and consumed one at a time. Generator comprehensions can be useful when you need to generate a large sequence of values that would be too memory-intensive to store in a list or other data structure.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply