# list problem

Alex Martelli aleax at aleax.it
Tue Sep 24 08:10:01 EDT 2002

```Duncan Booth wrote:

> Thorsten Kampe <thorsten at thorstenkampe.de> wrote in
> news:amp6i1\$7n9bi\$1 at ID- 77524.news.dfncis.de:
>
>> * Anthony Tuininga
>>> If you have list comprehensions available, use
>>>
>>> [b for a in x for b in a]
>>
>> reduce(lambda x, y: x + y, a) ?
>>
>
> If you are going to use reduce, then you would be better off writing:
>
>    import operator

Maybe (marginally).  But timing things is often a good idea:

import time, sys, operator

def alaAT(x):
return [b for a in x for b in a]

def alaTK(a):
return reduce(lambda x, y: x+y, a)

biggie = [ range(120) for i in range(160) ]

def timit(func, N=100):
repeat = [None] * N
start = time.clock()
for x in repeat: func(biggie)
stend = time.clock()
return "%2.2f %s" % (stend-start, func.__name__)

print sys.version
for i in range(3):
for func in alaAT, alaTK, alaDB, alaAM:
print timit(func)

[alex at lancelot linud]\$ python -O timit.py
2.2.1 (#2, Jul 15 2002, 17:32:26)
[GCC 2.96 20000731 (Mandrake Linux 8.1 2.96-0.62mdk)]
1.43 alaAT
2.75 alaTK
2.72 alaAM
1.42 alaAT
2.73 alaTK
2.66 alaAM
[alex at lancelot linud]\$

>From this measurement it's unclear whether there's anything to
choose between the versions using reduce, but Thorsten's original
proposal appears to be substantially better than any of them
(for these sizes of lists on this specific machine...) -- almost
a factor of 2, thus almost worth noticing if the performance
of this operation matters for the program being developed.

Alex

```