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 # yield values one by one
# call the generator function
for num in fun(5):
print(num)
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
Difference between return and yield in Python
The yield keyword in Python is similar to the return statement in that both are used for returning values. However, there are some key differences:
Feature | return | yield |
|---|---|---|
Execution | Terminates function execution | Pauses execution and maintains state |
| Memory Efficiency | Stores entire result in memory | Uses lazy evaluation, saving memory |
| Resumption | Function does not retain its state | Function resumes execution after yield |
Example 1 : Using yield
def fun(n):
for i in range(n):
yield i * i # Returns values one by one
a = fun(5)
for num in a:
print(num)
Output
0 1 4 9 16
Explanation: This code returns an iterator (generator) that computes values on the fly, avoiding high memory usage.
Example 2 : Using return
def fun(n):
res = []
for i in range(n):
res.append(i * i)
return res # returns the full list at once
a= fun(5)
print(a)
Output
[0, 1, 4, 9, 16]
Explanation: This code stores the entire list in memory and returns it at once.
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.
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"
gen = my_generator()
print(type(gen))
print(next(gen))
print(next(gen))
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():
num = 0
while True:
yield num
num += 1
gen = infinite_sequence()
for _ in range(10):
print(next(gen), 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 num in a:
if num % 2 == 0:
yield num
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):
words = text.split()
for word in words:
if word == keyword:
yield True
txt = "geeks for geeks"
search = fun(txt, "geeks")
print(sum(search))
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.
Related Articles
Python | yield Keyword – FAQs
What is yield in programming?
yieldis a keyword used in programming, especially in Python, to turn a function into a generator. When a function contains theyieldkeyword, it returns an iterator that can be used to iterate over a sequence of values. Unlike a typical function which runs to completion and returns a single value, a generator function can yield multiple values one at a time, pausing and resuming its state between each yield.
What is yield vs return in Python?
yield: Allows a function to return a value and pause its execution, saving its state. When called again, the function resumes execution right after theyieldstatement. This makes the function a generator.def count_up_to(max):
count = 1
while count <= max:
yield count
count += 1
counter = count_up_to(5)
for num in counter:
print(num)
return: Ends the execution of a function and returns a value to the caller. The function’s state is not saved and cannot be resumed.def get_sum(a, b):
return a + b
result = get_sum(3, 5)
print(result) # Output: 8
What are the disadvantages of yield in Python?
- Complexity: Using
yieldcan make the code harder to understand and maintain, especially for those unfamiliar with generators.- State Management: Managing the state of a generator function can be tricky, as it requires careful handling of where execution left off and what data was yielded.
- Limited Use Cases: Generators are not always the best choice for all situations. For instance, if you need to process all elements at once or require random access to the sequence, generators may not be suitable.
- Debugging Difficulty: Debugging generator functions can be more difficult compared to regular functions because of their stateful nature and the way they yield values.
Does yield stop execution?
Yes,
yieldstops execution temporarily. When a generator function encounters ayieldstatement, it returns the yielded value to the caller and pauses its execution. The state of the function is saved, so when the generator is iterated or resumed, execution continues from just after the lastyieldstatement.def simple_generator():
print("First yield")
yield 1
print("Second yield")
yield 2
print("Third yield")
yield 3
gen = simple_generator()
print(next(gen)) # Output: First yield\n1
print(next(gen)) # Output: Second yield\n2
print(next(gen)) # Output: Third yield\n3


