This question already has an answer here:
I have two ways to loop data, one using with for loop another with yield, I want to know what's the difference.
For Loop(get 100000 data)
data='select 100000 data from database' for d in date: do something with d
yield (get 1000 data every time,then query database 100 times)
def func(): data='select 1000 data from database' while date.count>0: yield data data = func() for d in data: do something with d
It depends on how your database implementation works.
In this case, it completely depends on what you do in func. If you generate the complete list at once, then you have no advantage of using yield over loop. If you generate it one by one, then yield will help.
Are you asking what yield does, or are you asking if it will be more efficient to split up a large database query?
Is date different from data? What is func() supposed to do? If date=data and the select line in supposed to represent a database read, and .count was a valid attribute describing how many results were returned, then the loop would yield the entire database read infinitely (if it was non-empty).
Do you mean: there is no difference between the two ways? thanks
Veelian: Functionally, no. Stylistically, yes.
they are functionally not the same, generators are not the same as iterators.
dnozay: That's a rather strange line of reasoning. If X is not the same Y doesn't mean that X and Y can't be used to do the same thing.
NPE, recursion and iteration are also not the same thing, even though people use it to calculate fibonacci numbers.