how to join array of integers?

Paul Rudin paul.nospam at rudin.co.uk
Sun Sep 16 20:25:22 CEST 2007


Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> writes:

> On Sat, 15 Sep 2007 15:56:40 +0200, Arnau Sanchez wrote:
>
>> js escribió:
>> 
>>>> On 9/15/07, Summercool <Summercoolness at gmail.com> wrote:
>> 
>>>> in Python... is the method to use  ",".join() ?  but then it must take
>>>> a list of strings... not integers...
>>>>
>>>> any fast method?
>> 
>>  > 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])
>
>
> Really? Why do you say that a generator expression is "better" than a 
> list comprehension?
>
>
>>>> import timeit
>>>> timeit.Timer("', '.join([str(i) for i in [1,2,3]])", "").repeat()
> [5.0969390869140625, 4.5353701114654541, 4.5807528495788574]
>>>> timeit.Timer("', '.join(str(i) for i in [1,2,3])", "").repeat()
> [11.651727914810181, 10.635221004486084, 10.522483110427856]
>
> The generator expression takes about twice as long to run, and in my 
> opinion it is no more readable. So what's the advantage?

If you do it with a decent size list they take more or less the same
time. You'd presumably expect the generator to use less memory; which
might be an advantage if you have large lists.

Isn't it odd that the generator isn't faster, since the comprehension
presumably builds a list first and then iterates over it, whereas the
generator doesn't need to make a list?



More information about the Python-list mailing list