how to join array of integers?
paul.nospam at rudin.co.uk
Mon Sep 17 17:57:24 CEST 2007
Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> writes:
> On Sun, 16 Sep 2007 19:25:22 +0100, Paul Rudin wrote:
>>> 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
> Did you try it,
> or are you guessing?
Well - I guessed first, otherwise it wouldn't have been worth trying :)
> What do you call a decent size?
I used 10,000.
>> You'd presumably expect the generator to use less memory; which
>> might be an advantage if you have large lists.
> Unfortunately, Python doesn't make it as easy to measure memory use as it
> does to time snippets of code, so that's just a hypothetical.
Well - as it turns out the list gets made anyway by the join method,
so in this case there's probably little difference. However there
(obviously) are siturations where a generator is going to save you a
significant memory over the similar list comprehension.
>> 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?
> Who says it doesn't need to make a list? string.join() needs a sequence.
The generator doesn't make a list. The implementation of str.join does
apparently needs a sequence and so makes a list from the generator
passed to it, which is presumably why you get essentially the same
performance once you factor out setup noise for small lists.
Although it's not clear to me why the join method needs a sequence
rather than just an iterator.
More information about the Python-list