![]() |
VOOZH | about |
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.
def generator_function():
yield value
value is the item that will be produced (yielded) by generator each time you call next() on it.
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.
0 1 2 3 4
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.
Generator functions behave like normal functions but use yield instead of return. They automatically create __iter__() and __next__() methods, making them iterable objects.
<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.
Here, we generate an infinite sequence of numbers using yield. Unlike return, execution continues after yield.
0 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.
[4, 6]
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.
yield can be useful in handling large data and searching operations efficiently without requiring repeated scans.
2
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.