All great answers, however a bit difficult for newbies.
I assume you have learned the return
statement.
As an analogy, return
and yield
are twins. return
means 'return and stop' whereas 'yield` means 'return, but continue'
- Try to get a num_list with
return
.
def num_list(n):
for i in range(n):
return i
Run it:
In [5]: num_list(3)
Out[5]: 0
See, you get only a single number instead ofrather than a list of them. return
never allows you prevail happily, just implements once and quit.
- There comes
yield
Replace return
with yield
:
In [10]: def num_list(n):
...: for i in range(n):
...: yield i
...:
In [11]: num_list(3)
Out[11]: <generator object num_list at 0x10327c990>
In [12]: list(num_list(3))
Out[12]: [0, 1, 2]
Now, you win to get all the numbers.
Comparing to return
which runs once and stops, yield
runs times you planed.
You can interpret return
as return one of them
, and yield
as return all of them
. This is called iterable
.
- One more step we can rewrite
yield
statement withreturn
In [15]: def num_list(n):
...: result = []
...: for i in range(n):
...: result.append(i)
...: return result
In [16]: num_list(3)
Out[16]: [0, 1, 2]
It's the core about yield
.
The difference between a list return
outputs and the object yield
output is:
You canwill always get [0, 1, 2] from a list object always whereas canbut only could retrieve them from 'the object yield
output' once. So, it has a new name generator
object as displayed in Out[11]: <generator object num_list at 0x10327c990>
.
In conclusion, as a metaphor to grok it:
return
andyield
are twinslist
andgenerator
are twins