1

I have two ways to loop data, one using with for loop another with yield, I want to know what's the difference.

  1. For Loop(get 100000 data)

    data='select 100000 data from database'
    
    for d in date:
        do something with d    
    
  2. 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
    
Mil0R3
  • 3,876
  • 4
  • 33
  • 61
  • It depends on how your database implementation works. – Waleed Khan Feb 16 '13 at 06:00
  • 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. – asheeshr Feb 16 '13 at 06:03
  • Are you asking what yield does, or are you asking if it will be more efficient to split up a large database query? – Seth Feb 16 '13 at 06:10
  • 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). – Paul Hankin Feb 16 '13 at 07:05

1 Answers1

0

Functionally, they're the same.

The main difference is that, in the second case, it's really easy to have several different "do something" blocks without repeating the SQL statement. In the first case, the "do something" is hard-coded.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • Do you mean: there is no difference between the two ways? thanks – Mil0R3 Feb 16 '13 at 06:16
  • @Veelian: Functionally, no. Stylistically, yes. – NPE Feb 16 '13 at 06:17
  • they are functionally not the same, generators are not the same as iterators. – dnozay Feb 16 '13 at 06:24
  • @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 Feb 16 '13 at 06:29
  • @NPE, recursion and iteration are also not the same thing, even though people use it to calculate fibonacci numbers. – dnozay Feb 16 '13 at 06:33