In Python, yield keyword is used to create generators, which are special types of iterators that allow values to be produced lazily, one at a time, instead of returning them all at once. This makes yield particularly useful for handling large datasets efficiently, as it allows iteration without storing entire sequence in memory.
For Example: Think of yield like a vending machine. Each time you press a button (call next()), it gives you one item and pauses. It remembers where it left off, so next time you press the button, it continues from there instead of starting over. This continues until all items are dispensed.
Why Do We Need yield Keyword?
- Supports Infinite Sequences: Lets you define generators that can yield an endless stream of values (e.g., Fibonacci series, real-time data).
- Enables Coroutine-like Behavior: Useful in asynchronous programming where a function needs to pause and resume later.
- Improves Testability: Makes functions easier to test by breaking execution into predictable steps.
- Builds Modular Pipelines: Encourages cleaner architecture by separating data production and consumption stages.
- Fine-Grained Control Over Iteration: Lets you customize exactly when and how values are produced, offering more flexibility than regular functions.
Syntax
def generator_function():
yield value
value is the item that will be produced (yielded) by generator each time you call next() on it.
Examples of yield
Example 1: Simple Generator to Yield Numbers Sequentially
This example demonstrates a simple generator function that yields numbers from 0 up to 4. It shows how yield can be used to produce a sequence one value at a time using a loop.
Python def fun(m): for i in range(m): yield i # call the generator function for n in fun(5): print(n)
Explanation: fun(m) generates numbers from 0 to m-1 using yield. Calling fun(5) returns a generator, which for loop iterates over, yielding values one by one until completion.
Example 2: Generator functions and yield
Generator functions behave like normal functions but use yield instead of return. They automatically create __iter__() and __next__() methods, making them iterable objects.
Python def my_generator(): yield "Hello world!!" yield "GeeksForGeeks" g = my_generator() print(type(g)) print(next(g)) print(next(g))
Output<class 'generator'> Hello world!! GeeksForGeeks
Explanation: my_generator() is a generator that yields "Hello world!!" and "GeeksForGeeks", returning a generator object without immediate execution, which is stored in gen.
Example 3: Generating an Infinite Sequence
Here, we generate an infinite sequence of numbers using yield. Unlike return, execution continues after yield.
Python def infinite_sequence(): n = 0 while True: yield n n += 1 g = infinite_sequence() for _ in range(10): print(next(g), end=" ")
Output0 1 2 3 4 5 6 7 8 9
Explanation: infinite_sequence() is an infinite generator that starts at 0, yielding increasing numbers. The for loop calls next(gen) 10 times, printing numbers from 0 to 9.
Here, we are extracting the even number from the list.
Python def fun(a): for n in a: if n % 2 == 0: yield n a = [1, 4, 5, 6, 7] print(list(fun(a)))
Explanation: fun(a) iterates over the list a, yielding only even numbers. It checks each element and if it's even (num % 2 == 0), it yields the value.
Example 5: Using yield as a boolean expression
yield can be useful in handling large data and searching operations efficiently without requiring repeated scans.
Python def fun(text, keyword): w = text.split() for n in w: if n == keyword: yield True txt = "geeks for geeks" s = fun(txt, "geeks") print(sum(s))
Explanation: fun(text, keyword) is a generator that splits text into words and checks if each word matches keyword. If a match is found, it yields True.
Advantages of using Yield
- Memory Efficiency: Since the function doesn’t store the entire result in memory, it is useful for handling large data sets.
- State Retention: Variables inside the generator function retain their state between calls.
- Lazy Evaluation: Values are generated on demand rather than all at once.
Disadvantages of using Yield
- Complexity: Using yield can make the code harder to understand and maintain, especially for beginners.
- State Management: Keeping track of the generator’s state requires careful handling.
- Limited Use Cases: Generators do not support indexing or random access to elements.
Related Posts
What does the yield keyword do in a Python function?
-
Exits the function immediately
-
-
Returns a value and pauses the function execution
-
Allocates memory dynamically
Explanation:
yield allows a function to return a value while maintaining its internal state, enabling it to resume where it left off.
What is the output of this code?
Python def fun(m): for i in range(m): yield i for n in fun(3): print(n, end=" ")
Explanation:
The generator yields values from 0 to m-1 using range(m).
Which built-in methods do generator objects support implicitly?
-
-
-
__iter__() and __next__()
-
Explanation:
Generator objects automatically implement the iterator protocol using __iter__() and __next__().
Quiz Completed Successfully
Your Score : 2/3
Accuracy : 0%
Login to View Explanation
1/3 1/3 < Previous Next >
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice
My Profile