top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is yield keyword in python and give an example?

+2 votes
573 views
What is yield keyword in python and give an example?
posted Feb 4, 2015 by Gnanendra Reddy

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

Yield is a keyword that is used like return, except the function will return a generator, so lets first understand the generator -

Generators are iterators, but you can only iterate over them once. It’s because they do not store all the values in memory, they generate the values on the fly:

>>> mygen = (x*x for x in range(3))
>>> for i in mygen:
...    print(i)

Output 
0
1
4

you can not perform for i in mygen a second time since generators can only be used once.

Now coming back to yield which by definition is a keyword that is used like return, except the function will return a generator, see the following example for more clarity -

>>> def createGenerator():
...    mylist = range(3)
...    for i in mylist:
...        yield i*i
...
>>> mygen = createGenerator() 
>>> print(mygen)

Output
0
1
4
answer Feb 4, 2015 by Salil Agrawal
already return keyword is there in python  i really didnt understand "for i in mygen a second time since generators can only be used once "sir please give me some more explanation
return will return after the first iteration and second&third would not even complete. Is this answers your query.
...