Python yield Keyword Tutorial

The yield keyword is used to return local variables without stopping the execution of the function or iteration. This means a single function or iterator execution may return multiple values by using multiple yields multiple times and multiple locations.

How Does yield Keyword Works?

The yield keyword is generally used with functions and returns a collection that contains the yield returned values. In the following example, we return a collection by calling the calculate() method and using the yield keyword. The returned collection can be iterated with a for loop and the returned values are assigned to the variable a and then printed to the standard output.

def calculate():
  yield 1
  yield 2
  yield 3
  yield 4

for a in calculate():

Leave a Comment