Grant Edwards wrote: > On 2007-09-15, Robert Kern <[EMAIL PROTECTED]> wrote: >> Grant Edwards wrote: >>> On 2007-09-15, Erik Jones <[EMAIL PROTECTED]> wrote: >>> >>>>>> print ''.join([str(i) for i in [1,2,3]]) >>>>> It's better to use generator comprehension instead of LC: >>>>> >>>>> ",".join(str(i) for i in [1, 2, 3]) >>>> Why is that? That entire expression must be evaluated to >>>> obtain the result, so what is the advantage of using a >>>> generator comprehension v. a list comprehension? >>> The generator avoids creating the intermediate list -- it >>> generates the intermediate values on the fly. For short >>> sequences it probably doesn't matter much. For a very long >>> list it's probably noticable. >> Not true. str.join() creates a list from the iterator if it is >> not already a list or a tuple. > > So the iterator avoids creating an intermediate list, but the > join method goes ahead and does it anyway?
Yup. >> In Objects/stringobject.c, look at string_join(); it calls >> PySequence_Fast() on the argument. Looking in >> Objects/abstract.c, we see that PySequence_Fast() >> short-circuits lists and tuples but builds a full list from >> the iterable otherwise. > > So what's the point of iterables if code is going to do stuff > like that when it wants to iterate over a sequence? Some code dealing with sequences can be recast in terms of iterators of unknown length. Some can't. Some are better cast in terms of iterators than sequences; some aren't. >> map() seems to reliably be the fastest option, > > Which is apparently going away in favor of the slower iterator > approach? It's only slower in this case. Of course, the main difference is where the loop takes place, in C or in Python. imap() appears to give the same performance as map(). -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list