Facebook Page Twitter Page LinkedIn Page
× Python Tutorial Python Advanced Python Resources Python Libraries


The Python yield keyword is used to return from a function. It is used like a return statement but it does not destroy the states of its local variable and when the function is called, the execution starts from the last yield statement.

Any function that contains a yield statement is also known as generator. Generator is an iterator that generates one value at a time. It is useful when working with large number of values which takes a lot of memory. Generator only deals with one value at a time, rather than storing all values in the memory.

Example:

In the below example, yield statement is used to create a generator function. The generator function returns square of numbers from 1 to 9.

#creating a generator
def Generator():
  for i in range(1,10):
    yield i*i

#printing the content of the generator
x = Generator()
for i in x:
  print(i)

The output of the above code will be:

1
4
9
16
25
36
49
64
81

❮ Python Keywords