How to Create a List Generator in Python?

Estimated read time 2 min read

In Python, you can create a list generator using a generator expression or a generator function.

  1. Using a Generator Expression:

A generator expression is a concise way to create a generator in Python. It is similar to a list comprehension, but instead of creating a list, it generates elements on-the-fly as they are requested. Here’s an example of a generator expression that generates even numbers from 0 to 10:

even_numbers = (x for x in range(0, 11) if x % 2 == 0)

In this example, we use the range() function to generate numbers from 0 to 10. The if statement filters the numbers to only include even numbers. We wrap the list comprehension in parentheses instead of square brackets to create a generator object.

  1. Using a Generator Function:

A generator function is a user-defined function that returns a generator object. It uses the yield keyword to return a value and pause the function execution until the next value is requested. Here’s an example of a generator function that generates Fibonacci numbers:

def fibonacci(n):
    a, b = 0, 1
    for i in range(n):
        yield a
        a, b = b, a + b

In this example, we define a function fibonacci that takes an integer n as an argument. We use a for loop to generate n Fibonacci numbers and use the yield keyword to return each number and pause the function execution until the next number is requested.

To use a generator, you can iterate over it using a for loop or use the next() function to get the next element. Here’s an example of iterating over a generator object:

even_numbers = (x for x in range(0, 11) if x % 2 == 0)
for number in even_numbers:
    print(number)

This will print all the even numbers from 0 to 10. Note that once all the elements have been generated, you cannot iterate over the generator again, and you need to create a new generator object.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply