What are Generators, Generator Functions, Generator Objects, and Yield?

What are Generators, Generator Functions, Generator Objects, and Yield?

Hello friends, in this article we will see how can we convert a generator to a list in Python. We will see all the methods and will also provide an easy and simple explanation to Convert Generator To List In Python.

What are Generators in Python?

The generator can be an object or a function that returns a generator object. So, we can say a generator is of two types- Generator-function and Generator-object.

Generator function

A generator function uses the yield(not return) keyword to return a value. So, in python, if a function uses the yield keyword, it automatically becomes a Generator function.

We can iterate over the values returned by the Generator function with a loop

Example:

def my_generator_fun():
    yield 1
    yield 2
    yield 3
    
for number in my_generator_fun():
    print(number)

Output:

1
2
3

Generator Object

A Generator object is an iterable object in Python like lists. A Generator object is the overall return value of a Generator function in Python. We can use the next() function to access the values of a Generator object.

Example:

def my_generator_fun():
    yield 1
    yield 2
    yield 3
    
my_generator_object = my_generator_fun()
    
print(next(my_generator_object))
print(next(my_generator_object))
print(next(my_generator_object))

Output:

1
2
3

Using next() over List

We will get the error if we will use next() with lists. We will get an error because next() works with iterators only.

Example:

my_list = [1,2,3]
    
print(next(my_list))
print(next(my_list))
print(next(my_list))

Output:

>>> %Run test.py
Traceback (most recent call last):
  File "D:\run for test\test.py", line 3, in <module>
    print(next(my_list))
TypeError: 'list' object is not an iterator

Video Tutorial for Generators in Python

Conclusion

In this article, we learned What are generators, How to use generator functions in Python? How to use Generator Objects in Python? What is the use of the Yield keyword in Generator functions in Python? We hope this article on Generators will explain most of the concepts related to generators in Python you will ever need now or in the future.

Thank you for reading this article.


Also Read:

Share:

Author: Harry

Hello friends, thanks for visiting my website. I am a Python programmer. I, with some other members, write blogs on this website based on Python and Programming. We are still in the growing phase that's why the website design is not so good and there are many other things that need to be corrected in this website but I hope all these things will happen someday. But, till then we will not stop ourselves from uploading more amazing articles. If you want to join us or have any queries, you can mail me at admin@copyassignment.com Thank you