convert list of tuples into several lists

Oliver Eichler oliver.eichler at dspsolutions.de
Thu Feb 10 04:16:35 EST 2005


Pierre Barbier de Reuille wrote:
> Best answer is : try it :)
> use the "timeit" module (in the standard lib) to do so ...

Ok,

import timeit

s = """\
a,b,c1,c2 = zip(*[(x[2],x[4], x[2]-x[1], x[2] - x[3]) for x in z])
"""

t = timeit.Timer(stmt=s,setup="z = [(1,2,3,4,5)]*1000")
print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)

s ="""\
for x in z:
  a = x[2]
  b = x[4]
  c1 = x[2] - x[1]
  c2 = x[2] - x[3]
"""

t = timeit.Timer(stmt=s,setup="z = [(1,2,3,4,5)]*1000")
print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)

for 30 elements:
oeichler at frog:~/tmp> python test.py
32.90 usec/pass
21.53 usec/pass

for 100 elements:
oeichler at frog:~/tmp> python test.py
103.32 usec/pass
70.91 usec/pass

for 100 elements:
oeichler at frog:~/tmp> python test.py
1435.43 usec/pass
710.55 usec/pass

What do we learn? It might look elegant but it is slow. I guess mainly
because I do the iteration twice with the zip command. The 1000 element run
seems to show what Guido means with "abuse of the argument passing
machinery"

Learned my lesson :)

Thanks to all

Oliver





More information about the Python-list mailing list