how to join array of integers?

Grant Edwards grante at
Sun Sep 16 00:36:08 CEST 2007

On 2007-09-15, Robert Kern <robert.kern at> wrote:
> Grant Edwards wrote:
>> On 2007-09-15, Erik Jones <erik at> 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?

> 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?

> map() seems to reliably be the fastest option,

Which is apparently going away in favor of the slower iterator

> and list comprehensions seem to slightly edge out generator
> comprehensions if you do the timings.

Grant Edwards                   grante             Yow!  Clear the
                                  at               laundromat!! This
                                 whirl-o-matic just had a
                                                   nuclear meltdown!!

More information about the Python-list mailing list