Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to use yield in Python best?

Tags:

python

yield

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.

like image 385
whi Avatar asked Oct 25 '11 02:10

whi


People also ask

When should I use yield Python?

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.

Why do we need yield in Python?

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.

Is yield faster Python?

At least in this very simple test, yield is faster than append.

What is the purpose of a yield statement?

The yield statement returns a generator object to the one who calls the function which contains yield, instead of simply returning a value.


1 Answers

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.

like image 150
murgatroid99 Avatar answered Oct 11 '22 17:10

murgatroid99