Just use sum
if you don't have a lot of tuples.
>>> tupleOfTuples = ((1, 2), (3, 4), (5,))
>>> sum(tupleOfTuples, ())
(1, 2, 3, 4, 5)
>>> list(sum(tupleOfTuples, ())) # if you really need a list
[1, 2, 3, 4, 5]
If you do have a lot of tuples, use list comprehension or chain.from_iterable to prevent the quadratic behavior of sum
.
Micro-benchmarks:
Python 2.6
Long tuple of short tuples
$ python2.6 -m timeit -s 'tot = ((1, 2), )*500' '[element for tupl in tot for element in tupl]'
10000 loops, best of 3: 134 usec per loop
$ python2.6 -m timeit -s 'tot = ((1, 2), )*500' 'list(sum(tot, ()))'
1000 loops, best of 3: 1.1 msec per loop
$ python2.6 -m timeit -s 'tot = ((1, 2), )*500; from itertools import chain; ci = chain.from_iterable' 'list(ci(tot))'
10000 loops, best of 3: 60.1 usec per loop
$ python2.6 -m timeit -s 'tot = ((1, 2), )*500; from itertools import chain' 'list(chain(*tot))'
10000 loops, best of 3: 64.8 usec per loop
Short tuple of long tuples
$ python2.6 -m timeit -s 'tot = ((1, )*500, (2, )*500)' '[element for tupl in tot for element in tupl]'
10000 loops, best of 3: 65.6 usec per loop
$ python2.6 -m timeit -s 'tot = ((1, )*500, (2, )*500)' 'list(sum(tot, ()))'
100000 loops, best of 3: 16.9 usec per loop
$ python2.6 -m timeit -s 'tot = ((1, )*500, (2, )*500); from itertools import chain; ci = chain.from_iterable' 'list(ci(tot))'
10000 loops, best of 3: 25.8 usec per loop
$ python2.6 -m timeit -s 'tot = ((1, )*500, (2, )*500); from itertools import chain' 'list(chain(*tot))'
10000 loops, best of 3: 26.5 usec per loop
Python 3.1
Long tuple of short tuples
$ python3.1 -m timeit -s 'tot = ((1, 2), )*500' '[element for tupl in tot for element in tupl]'
10000 loops, best of 3: 121 usec per loop
$ python3.1 -m timeit -s 'tot = ((1, 2), )*500' 'list(sum(tot, ()))'
1000 loops, best of 3: 1.09 msec per loop
$ python3.1 -m timeit -s 'tot = ((1, 2), )*500; from itertools import chain; ci = chain.from_iterable' 'list(ci(tot))'
10000 loops, best of 3: 59.5 usec per loop
$ python3.1 -m timeit -s 'tot = ((1, 2), )*500; from itertools import chain' 'list(chain(*tot))'
10000 loops, best of 3: 63.2 usec per loop
Short tuple of long tuples
$ python3.1 -m timeit -s 'tot = ((1, )*500, (2, )*500)' '[element for tupl in tot for element in tupl]'
10000 loops, best of 3: 66.1 usec per loop
$ python3.1 -m timeit -s 'tot = ((1, )*500, (2, )*500)' 'list(sum(tot, ()))'
100000 loops, best of 3: 16.3 usec per loop
$ python3.1 -m timeit -s 'tot = ((1, )*500, (2, )*500); from itertools import chain; ci = chain.from_iterable' 'list(ci(tot))'
10000 loops, best of 3: 25.4 usec per loop
$ python3.1 -m timeit -s 'tot = ((1, )*500, (2, )*500); from itertools import chain' 'list(chain(*tot))'
10000 loops, best of 3: 25.6 usec per loop
Observation:
sum
is faster if the outer tuple is short.
list(chain.from_iterable(x))
is faster if the outer tuple is long.