What does the “yield” keyword do in Python?

PythonServer Side ProgrammingProgramming

The yield keyword is used in generator. To understand its behaviour let us first see what are iterables. Python objects list, file, string etc are called iterables. Any object which can be traversed using for .. in syntax is iterable. Iterator object is also an iterable, but it can be iterated upon only once. Iterator object can be obtained form any iterable using iter() function and it has next() method using which iteration is done.

>>> L1 = [1,2,3,4]
>>> I1 = iter(L1)
>>> while True:
   try:
      print (next(I1))
   except StopIteration:
sys.exit()

The generator appears similar to a function, but it yields successive items in the iterator by yield keyword.

When a generator function is called, it returns a iterator object without even beginning execution of the function. When the next() method is called for the first time, the function starts executing until it reaches the yield statement, which returns the yielded value. The yield keeps track i.e. remembers the last execution and the second next() call continues from previous value.

Following example generates an iterator containing numbers in Fibonacci series. Each call to generator function fibo() yields successive element in the Fibonacci series.

import sys
def fibo(n):
   a,b=0,1
   while True:
      if a>n : return
      yield a
      a, b = b, a+b
f = fibo(20)
while True:
   try:
      print (next(f))
   except StopIteration:
      sys.exit()
raja
Published on 15-Jan-2018 00:17:12
Advertisements