Skip to content

Python generator to list

  • by

A Python generator is a special type of iterable that allows you to iterate over a sequence of values one at a time, without storing them all in memory at once. Generators are particularly useful for processing large datasets or infinite sequences. There are several ways to convert a generator to a list in Python.

  1. Using the list() function:
  2. Using the unpack operator *:
  3. Using list comprehension:
  4. Using the append() function:

Python generator to list example

Let’s go through each of the methods mentioned:

list() function: You can directly pass the generator to the list() function to convert it into a list.

def square_generator(n):
    for i in range(n):
        yield i ** 2

squares = square_generator(5)
squares_list = list(squares)

print(squares_list)  # Output: [0, 1, 4, 9, 16]

Unpack operator *: You can use the unpack operator * to unpack the generator’s values into a list.

def square_generator(n):
    for i in range(n):
        yield i ** 2

squares = square_generator(5)
squares_list = [*squares]

print(squares_list)  # Output: [0, 1, 4, 9, 16]

List comprehension: You can use list comprehension to iterate through the generator and create a list.

def square_generator(n):
    for i in range(n):
        yield i ** 2

squares = square_generator(5)
squares_list = [x for x in squares]

print(squares_list)  # Output: [0, 1, 4, 9, 16]

append() function: While you can technically use the append() function within a loop to build a list, it’s not a common approach for converting a generator to a list, as it requires more manual handling.

def square_generator(n):
    for i in range(n):
        yield i ** 2

squares = square_generator(5)
squares_list = []
for x in squares:
    squares_list.append(x)

print(squares_list)

Output:

Python generator to list

All of these methods will achieve the same result: converting the values generated by the generator into a list. The first three methods are more concise and idiomatic in Python. The fourth method using append() is less common, but it’s important to understand as it demonstrates how you can manually build a list from the generator’s values.

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