yield Keyword - Python
In Python, the 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 the entire sequence in memory.
Example:
def fun(m):
for i in range(m):
yield i
# call the generator function
for n in fun(5):
print(n)
Output
0 1 2 3 4
Explanation: fun(m) generates numbers from 0 to m-1 using yield. Calling fun(5) returns a generator, which the for loop iterates over, yielding values one by one until completion.
Syntax
def gen_func(m):
for i in range(m):
yield i # Produces values one at a time
Examples of yield in Python
Example 1: Generator functions and yield
Generator functions behave like normal functions but use yield instead of return. They automatically create the __iter__() and __next__() methods, making them iterable objects.
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 2: Generating an Infinite Sequence
Here, we generate an infinite sequence of numbers using yield. Unlike return, execution continues after yield.
def infinite_sequence():
n = 0
while True:
yield n
n += 1
g = infinite_sequence()
for _ in range(10):
print(next(g), end=" ")
Output
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.
Example 3: Extracting even numbers from list
Here, we are extracting the even number from the list.
def fun(a):
for n in a:
if n % 2 == 0:
yield n
a = [1, 4, 5, 6, 7]
print(list(fun(a)))
Output
[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.
Example 4: Using yield as a boolean expression
yield can be useful in handling large data and searching operations efficiently without requiring repeated scans.
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))
Output
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.
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 Articles