What does the yield keyword do in Python?
To understand what
yield
does, you must understand what generators are. And before generators come iterables.Everything you can use “
for... in...
” on is an iterable;lists
,strings
, files…These iterables are handy because you can read them as much as you wish, but you store all the values in memory and this is not always what you want when you have a lot of values.
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:
..
Yield
is a keyword that is used likereturn
, except the function will return a generator... And it works because Python does not care if the argument of a method is a list or not. Python expects iterables so it will work with strings, lists, tuples and generators! This is called duck typing and is one of the reason why Python is so cool.
.. In a nutshell: a generator is a lazy, incrementally-pending list, and
yield
statements allow you to use function notation to program the list values the generator should incrementally spit out.