Update: Flattening using extend but without comprehension and without using list as iterator (fastest)
After checking the next answer to this that provided a faster solution via a list comprehension with dual for
I did a little tweak and now it performs better, first the execution of list(...) was dragging a big percentage of time, then changing a list comprehension for a simple loop shaved a bit more as well.
The new solution is:
l = []
for row in output: l.extend(row)
The old one replacing list
with []
(a bit slower but not much):
[l.extend(row) for row in output]
Older (slower):
Flattening with list comprehension
l = []
list(l.extend(row) for row in output)
some timeits for new extend and the improvement gotten by just removing list(...) for [...]:
import timeit
t = timeit.timeit
o = "output=list(zip(range(1000000000), range(10000000))); l=[]"
steps_ext = "for row in output: l.extend(row)"
steps_ext_old = "list(l.extend(row) for row in output)"
steps_ext_remove_list = "[l.extend(row) for row in output]"
steps_com = "[item for sublist in output for item in sublist]"
print(f"{steps_ext}\n>>>{t(steps_ext, setup=o, number=10)}")
print(f"{steps_ext_remove_list}\n>>>{t(steps_ext_remove_list, setup=o, number=10)}")
print(f"{steps_com}\n>>>{t(steps_com, setup=o, number=10)}")
print(f"{steps_ext_old}\n>>>{t(steps_ext_old, setup=o, number=10)}")
Time it results:
for row in output: l.extend(row)
>>> 7.022608777000187
[l.extend(row) for row in output]
>>> 9.155910597999991
[item for sublist in output for item in sublist]
>>> 9.920002304000036
list(l.extend(row) for row in output)
>>> 10.703829122000116
[(12.2817, 12.2817), (0, 0), (8.52, 8.52)]
is already a 3x2 matrix !? or did i miss something ? – Prunelle[item for sublist in output for item in sublist]
works perfectly and has the advantage that your inner tuples could also be lists; more generally any combination of inner and outer iterable works – Keg