flatten a level one list

Peter Otten __peter__ at web.de
Thu Jan 12 04:05:04 EST 2006


Tim Hochberg wrote:

> Here's one more that's quite fast using Psyco, but only average without
> it.
 
> def flatten6():
>      n = min(len(xdata), len(ydata))
>      result = [None] * (2*n)
>      for i in xrange(n):
>              result[2*i] = xdata[i]
>              result[2*i+1] = ydata[i]

I you require len(xdata) == len(ydata) there's an easy way to move the loop
into C:

def flatten7():
    n = len(xdata)
    assert len(ydata) == n
    result = [None] * (2*n)
    result[::2] = xdata
    result[1::2] = ydata
    return result

$ python -m timeit 'from flatten import flatten6 as f' 'f()'
1000 loops, best of 3: 847 usec per loop
$ python -m timeit 'from flatten import flatten7 as f' 'f()'
10000 loops, best of 3: 43.9 usec per loop

Peter



More information about the Python-list mailing list