When to use yield instead of return in Python?

PythonServer Side ProgrammingProgramming

In short, whenever control reach the return statement in your program, the execution of the program is terminated and the remaining statements will not executed.

However, in case of yield, whenever control reach the yield statement in your program, the execution of your program is paused and later we can continue other statements in function.

Let’s understand both the statements in detail.

Yield

Using yield statement in a function makes the function a generator function which can be used in a loop. When the function is running and the yield statement exeucutes, the value after the yield is passed back to the loop that called it. The next time the loop iterates, the function starts immediately after the yield statements.

def func():
   yield 1
   yield 2
   yield 3

for num in func():
   print(num * num)

output

1
4
9

In above program, the loop that invokes the function will complete when the func function completes – either meets the end of the function (func()) or a return statement.

However, any new loop that uses the same generator function will execute the function from the start again.

Return

A return statement,

  • Used to stop the execution of a function and optionally return a value to the caller. A function which has a return (but not a yield) cannot be used in a loop (unlike the yield above).

  • If a function which has previously executed is called again, the function begins execution from the start (unlike the yield above).

When to use return or yield?

It is recommended to use yield when we want to iterate over a sequence however, because of resource constraints or simply don’t want to store the entire sequence in memory. For other cases we can think of using return statement.

Let’s look at another program using yield statement to generate square of integer number.

def Square():
   i = 1;
   # An Infinite loop to generate squares
   while True:
      yield i*i
      i += 1 # Next execution resumes from this point
for num in Square():
   if num > 100:
      break
   print(num)

output

1
4
9
16
25
36
49
64
81
100

The yield statement is generally not used in the try clause of a try …. finally block because there’s no guarantee that the generator will ever be resumed, hence no guarantee that the finally block will ever get executed.

raja
Published on 02-May-2019 12:25:48
Advertisements