different ways to creating two lists from one
Alex Martelli
aleax at aleax.it
Wed Oct 29 16:06:56 EST 2003
Todd MacCulloch wrote:
> Suppose I have a master list and I need to create two derived lists,
> something like:
>
> s0 = [2,3,4]
> s1 = [x + x for x in s0]
> s2 = [x * x for x in s0]
>
> But suppose generating s0 is expensive and/or s0 is big. In otherwords I'd
> like to go over only once and I don't want to keep it around any longer
> than I have to.
>
> I could do something like:
>
> for a, b in [(x + x, x * x) for x in s0]:
> s1.append(a)
> s2.append(b)
>
> Is there a better / cleaner way that I'm missing?
Try timing your solutions, with an s0 as long as you want: I would be
very surprised if the first approach wasn't faster than the second one.
Assuming it's impossible to loop repeatedly on s0 AND the thing is too
huge to store anywhere, you can turn a sequence of pairs into a pair
of sequences with zip(*seqofpairs), but, again, you should measure
the speed rather than assuming the "cool" solution is fast:-).
Alex
More information about the Python-list
mailing list