Python Generator to List: A Beginner Guide – Python Tutorial

By | January 27, 2022

It is very easy to convert python generator to list. In this tutorial, we will introduce you how to do.

Generator in python

In python, we can use yield statement to create a generator. Here is the tutorial:

Understand Python yield Statement for Beginners – Python Tutorial

We can not get the length of a generator, which mean we can not use a len() function on it.

For example:

def batcher():
    for i in range(10):
        yield  i

n = batcher()
print(n)
print(len(n))

Run this code, we will get:

<generator object batcher at 0x7fae7d202308>
TypeError: object of type 'generator' has no len()

However, we can convert it to python list to compute its length.

Python generator to list

We can use python list() function to convert a generator to a list. Here is an example:

n = batcher()
x = list(n)
print(len(x))

Run this code, we will get: 10

Leave a Reply