I know how yield
works. I know permutation, think it just as a math simplicity.
But what's yield
's true force? When should I use it? A simple and good example is better.
We should use yield when we want to iterate over a sequence, but don't want to store the entire sequence in memory. Yield is used in Python generators. A generator function is defined just like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return.
yield in Python can be used like the return statement in a function. When done so, the function instead of returning the output, it returns a generator that can be iterated upon. You can then iterate through the generator to extract items. Iterating is done using a for loop or simply using the next() function.
At least in this very simple test, yield is faster than append.
The yield statement returns a generator object to the one who calls the function which contains yield, instead of simply returning a value.
yield
is best used when you have a function that returns a sequence and you want to iterate over that sequence, but you do not need to have every value in memory at once.
For example, I have a python script that parses a large list of CSV files, and I want to return each line to be processed in another function. I don't want to store the megabytes of data in memory all at once, so I yield
each line in a python data structure. So the function to get lines from the file might look something like:
def get_lines(files): for f in files: for line in f: #preprocess line yield line
I can then use the same syntax as with lists to access the output of this function:
for line in get_lines(files): #process line
but I save a lot of memory usage.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With