flatten a level one list

Peter Otten __peter__ at web.de
Fri Jan 13 10:03:49 CET 2006


bonono at gmail.com wrote:

>> Creating a list via list/map/filter just for the side effect is not only
>> bad taste,
>>
>> ~ $ python -m timeit -s'a = zip([range(1000)]*2)' 'lst=[];ext=lst.extend'
>> 'for i in a: ext(i)'
>> 1000000 loops, best of 3: 1.23 usec per loop
>> ~ $ python -m timeit -s'a = zip([range(1000)]*2)'
>> 'lst=[];filter(lst.extend, a)'
>> 1000000 loops, best of 3: 1.63 usec per loop
>>
>> it is also slower than an explicit loop. Don't do it.
>>
> Hi, but I found this result instead :
> 
> bonono at moresing:~$ python ~/lib/python2.4/timeit.py -s "a=range(10000);
> b=zip(*[a]*2); l=[None]*len(a)*2; e=l.extend" "l[::2]=b;l[1::2]=b"
> 100 loops, best of 3: 6.22 msec per loop
> bonono at moresing:~$ python ~/lib/python2.4/timeit.py -s "a=range(10000);
> b=zip(*[a]*2); l=[]; e=l.extend" "filter(e,b)"
> 100 loops, best of 3: 7.25 msec per loop
> bonono at moresing:~$ python ~/lib/python2.4/timeit.py -s "a=range(10000);
> b=zip(*[a]*2); l=[]; e=l.extend" "for x in b: e(x)"
> 100 loops, best of 3: 10.7 msec per loop
> bonono at moresing:~$
> 
> So it seems to be faster than explicit loop. By localizing the l.extend
> name binding, its speed is only 20% slower than  the fastest method.
> May be I have done something wrong in the test ?

I hate to admit it but /my/ post had a bug:

zip([range(1000)]*2) should have been zip(*[range(1000)]*2).

filter() may be ugly, but faster it is.

Peter




More information about the Python-list mailing list