Python Conversion Programs

Convert Generator To List In Python

Last updated January 31, 2024 by Jarvis Silva

Looking for a tutorial on how to convert generator to list in python then you are at the right place, a generator is like a normal function but instead of using the return keyword a generator function uses a yield keyword, when a function uses yield keyword it is called as a generator below is an example.

# Normal Function
def normal_func():
    return 1

# Generator
def gen_func():
    yield 1

When we print the generator function it returns a generator object, so our goal is to convert the generator function into a list, The list will contain all the yield values of the generator.

Convert Generator To List In Python Code 

def nums_gen():
    yield 1
    yield 2
    yield 3
    yield 4
    yield 5
# prints a generator object    

# converting generator to list using list()
nums_gen = list(nums_gen())

# prints a list

Above is the python program to convert a generator to list, the code defines a generator function that produces a sequence of numbers, we use the list() function to converted result of generator function to list the code gives below output.

[1, 2, 3, 4, 5]

You can run this code and see the result yourself by using this online python compiler or you can run it on your machine

As you can see, we have successfully converted a generator object to list in python, I hope you found this tutorial helpful and useful, do share this tutorial with your friends who might need this or find it helpful.

Here are some more python programs you will find helpful:

I hope you found what you were looking for from this python tutorial and if you want more python tutorials like this, do join our Telegram channel to get updated.

Thanks for reading, have a nice day 🙂