What is yield in Python?

Last updated 3 years ago | 1155 views 75     5

Tags:- Python

yield is a keyword beares the ability to turn any function into a generator.  Much like the standard return keyword, but returns a generator object. It is also true that one function may observe multiple yields.

def odds(n):
    odd=[i for i in range(n+1) if i%2!=0]
    for i in odd:
        yield i


for i in odds(8):
    print(i)

The output of the above code is

1
3
5
7