Skip to content

Instantly share code, notes, and snippets.

@mikolajb
Created October 9, 2011 23:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikolajb/1274348 to your computer and use it in GitHub Desktop.
Save mikolajb/1274348 to your computer and use it in GitHub Desktop.
python flatten test
from itertools import chain, product
from time import time
REPEAT = 10000
for s1, s2 in product([10, 100], repeat=2):
print "%i tuples with %i elements each" % (s2, s1)
a = [tuple(range(s1)) for i in range(s2)]
t = time()
for i in range(REPEAT):
b = [j for i in a for j in i]
print "comprehensions:", time() - t
t = time()
for i in range(REPEAT):
b = reduce(lambda x, y: x + list(y), a, [])
print "reduce: ", time() - t
t = time()
for i in range(REPEAT):
b = list(chain.from_iterable(a))
print "chain: ", time() - t
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment