simple way to un-nest (flatten?) list

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Mon Nov 6 18:56:03 EST 2006


djc:
> As it is possible that the tuples will not always be the same word in
> variant cases
> result = sum(r.values(), ())
>   will do fine and is as simple as I suspected the answer would be.

It is simple, but I suggest you to take a look at the speed of that
part of your code into your program. With this you can see the
difference:

from time import clock
d = dict((i,range(300)) for i in xrange(300))

t = clock()
r1 = sum(d.values(), [])
print clock() - t

t = clock()
r2 = []
for v in d.values(): r2.extend(v)
print clock() - t

assert r1 == r2

Bye,
bearophile




More information about the Python-list mailing list