yield Keyword in python

yield Keyword in Python

Python, a versatile and dynamic programming language, offers a wide array of features that make it a favorite among developers. One such feature is the “yield” keyword, which plays a crucial role in defining generator functions.

yield keyword in python

Python yield Keyword

The “yield” keyword in Python is primarily used to create generator functions. Generator functions are a special type of function that can be paused and resumed during execution, allowing them to generate values on-the-fly without storing them in memory.

When you use “yield” inside a function, it transforms that function into a generator. The “yield” statement is used to produce a value from the generator, and it temporarily suspends the function’s state until the next value is requested.

Basic Example of Generator Function:

Run
def simple_generator():
    yield 1
    yield 2
    yield 3

# Using the generator function
gen = simple_generator()
print(next(gen))  
print(next(gen))  
print(next(gen))  

Output : 

1
2
3

If you need to generate an iterable that doesn’t load all the data into memory at once or when working with enormous datasets, generator functions can be especially helpful. They are frequently used with loops and in circumstances where you need to randomly generate values.

def generate_numbers(n):
    for i in range(n):
        yield i

Advantages of yield Keyword:

  • Memory-efficient
  • Supports lazy evaluation
  • Enables infinite sequences
  • Enhances code readability

Disadvantages of yield Keyword:

  • May introduce complexity
  • Not suitable for all scenarios
  • Requires a good understanding of generators

Difference Between yield and return:

While “return” terminates a function and passes a value back to the caller, “yield” merely pauses the function, allowing it to be resumed later. This fundamental difference sets them apart in terms of functionality and use cases. “Yield” temporarily suspends a function, allowing it to be resumed later, while “return” terminates a function and passes a value back to the caller.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription