Open In App

Difference between Generator and Normal Function

Last Updated : 25 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Normal functions in Python are used for traditional computation tasks, with execution proceeding from start to finish, typically returning a single result. On the other hand, generator functions employ the `yield` statement to produce values lazily, preserving their state across multiple calls. This allows generators to efficiently handle large datasets or infinite sequences by yielding values one at a time and pausing execution when necessary, making them a valuable tool for memory-efficient and iterative tasks. In this article, we’ll look into Python generator functions and normal function differences i.e. how different are their syntax, how is data handled, and practical applications.

What are Python Generators?

Generator functions in Python make it easy to generate data, allowing for efficient memory utilization and lazy evaluation. That is totally different from normal functions, which run completely and return a single value, but generator functions simply employ the ‘yield’ keyword to generate values one at a time as the condition is stated. Because of this difference, generator functions are suited for working with enormous datasets or infinite sequences.

Yield statement

Yield statement allows a generator function to produce a value to the caller without losing the current state of the function. When the generator function is called again, execution resumes from where it left off, continuing to yield values one at a time. 

Let us see its syntax

def generator_function():
# Initialization or setup if needed
while condition:
# Calculate or generate a value
yield value_to_yield
# Logic to be applied if necessary

Now we will see an example of a generator function to understand it better:

Python3




# generator function
def Square():
     
    number = 2
     
    #Create infinite loop
    while True:
        # Yield the current value of 'number'
        yield number
         
        # Calculate the square of 'number' and update its value
        number *= number
 
# Create a generator object 'Sq' by calling the 'Square()' generator function
Sq = Square()
 
# Function call
print(next(Sq))  # Output: 2
 
  
print(next(Sq))  # Output: 4


Output

2
4



Normal function in Python

Normal function performs a specific task and can be called from other parts of the program. Also normal function  return a single value and terminate the session.

Python3




# generator function named square()
def square():
    number = 2
     
    # Create infinite loop
    while True:
        # Yield the current value of 'number'
        yield number
         
        # Calculate the square of 'number' and update its value
        number *= number
 
 
# Define a function to retrieve the next square from the generator.
def get_next_square():
    global number_generator
    try:
        # Try to get the next square from the existing generator 
        return next(number_generator)
    except NameError:
        # If 'number_generator' is not defined , initialize it
        number_generator = square()
         
        # Return the first square from the newly created generator.
        return next(number_generator)
 
 
#  function call  to retrieve the next square and print it.
print(get_next_square())  # Output: 2
 
print(get_next_square())  # Output: 4


Output

2
4




As you can see, the generator function uses the yield keyword instead of return and generates values as they are needed, rather than creating a list of all values at once.

Difference between generator and normal function

The generator function in Python is normally defined like a normal function, using the @’ keyword. If we need to generate value Generator functions make use of the yield keyword rather than using return. The major difference between the generator and normal function may be that the Generator function runs when the next() function is called and not by its name as in the case of normal functions.

Scope Generator Normal
Execution They can be paused in the middle of execution and resumed     They runs to completion and returns a value
Return value  They can return multiple values through multiple iterations. They returns a single value (or none)
Memory usage They keeps the current value in memory,   They create a large amount of memory overhead  
Usage They are used generate values that can be iterated over.   They are used when to perform a task and return a result.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads