How to Create a List Generator Using List Comprehension in Python?

Estimated read time 2 min read

A list comprehension is a concise way to create a list in Python. To create a list generator using list comprehension, you can simply wrap the list comprehension inside parentheses instead of square brackets. This will create a generator object instead of a list.

Here is an example of creating a list generator 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.

You can use a generator object in the same way as a list, but it generates the items on-the-fly as they are needed, rather than creating the whole list at once. This can be useful when working with large datasets, as it saves memory by only generating items as needed.

To access the elements of a generator, you can use the next() function. Here’s an example:

even_numbers = (x for x in range(0, 11) if x % 2 == 0)
print(next(even_numbers))  # Output: 0
print(next(even_numbers))  # Output: 2
print(next(even_numbers))  # Output: 4

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