Skip to main content

Generators in Python

In Python,Generators are simple functions which return an iterable set of objects, with a sequence of values in a special way. It is a simple way of creating iterators but with a different approach. It use the Python yield keyword instead of return. It can be used in a for loop.

Generators used to control the iteration behaviour of a loop. It is similar to a function returning an array.  A generator has parameter, which can be called and it generates a sequence of numbers. 

As function, used to return a whole array but, generator yields one value at a time which requires less memory.

Generator functions allow us to declare a function that behaves just like an iterator, allowing programmers to make an iterator in a fast, easy, and clean way. An iterator is an object that can be iterated or looped upon. It is used to abstract a container of data to make it behave like an iterable object. 

Generators are very easy to implement, but difficult to understand.

Example:

def Generator():
    print("Name:")
    yield "abc"
       
x = Generator()  
print(next(x))

Output:

Name:
'abc'
Tags
Submitted by devanshi.srivastava on August 3, 2021

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.