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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
yieldis 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
yieldeach line in a python data structure. So the function to get lines from the file might look something like:I can then use the same syntax as with lists to access the output of this function:
but I save a lot of memory usage.