Skip to content

Python List Generator

  • by

A Python list generator is a concise and efficient way to create lists using a compact syntax. Python provides two main constructs for generating lists: list comprehensions and generator expressions. Both of these constructs allow you to create lists based on existing sequences or ranges with optional filtering and transformation operations.

List Comprehensions: List comprehensions are a concise way to create lists by applying an expression to each item in an existing sequence (e.g., another list, range, string, etc.). They also allow for optional filtering based on conditions.

new_list = [expression for item in sequence if condition]

Generator Expressions: Generator expressions are similar to list comprehensions, but instead of creating a list in memory, they create an iterator, which generates values one at a time. This is more memory-efficient for large datasets.

generator = (expression for item in sequence if condition)

Generator expressions are useful when you don’t need to store the entire list in memory at once and want to iterate over the values one by one.

Both list comprehensions and generator expressions are powerful tools for generating lists in a concise and readable manner. The choice between them depends on whether you need to store the entire list or prefer to work with an iterator for memory efficiency.

Python List Generator example

Simple example code.

Example 1: Creating a list of squares of numbers from 0 to 9.

squares = [x ** 2 for x in range(10)]
print(squares)

Example 2: Creating a list of even numbers from 0 to 9.

even_numbers = [x for x in range(10) if x % 2 == 0]
print(even_numbers)

Example 3: Creating a generator for the squares of numbers from 0 to 9.

square_generator = (x ** 2 for x in range(10))
for square in square_generator:
    print(square)

Output:

Python List Generator

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading