For the following:
tup = ((element1, element2),(value1, value2))
I have used:
part1, part2 = tup
tup_to_list = [*part1, *part2]
Is there a cleaner way to do so? Is there "double unpacking"?
If you're looking to flatten a general tuple of tuples, you could:
flattened_tup = tuple(j for i in tup for j in i)
import itertools
flattened_tup = tuple(itertools.chain.from_iterable(tup))
tup = part1+part2
python adds the objects of tuples behind each other during addition
If there is no harm in using loops then you could try this
[tupl for tuploftupls in tup for tupl in tuploftupls]
Here's the same kind of question
For the sake of performance, if I had to repeatedly perform such concatenations over small tup
s, I would go for the builtin function sum
, providing it with an empty tuple as starting value, i.e. sum(tup, ())
. Otherwise, I would go for itertools.chain.from_iterable
-based solution of @Lucas.
Performance comparisons.
Commonalities
import itertools
import timeit
scripts = {
'builtin_sum' : "sum(tup, t0)",
'chain_from_iterable' : "(*fi(tup),)",
'nested_comprehension': "[tupl for tuploftupls in tup for tupl in tuploftupls]",
}
env = {
'fi' : itertools.chain.from_iterable,
't0' : (),
}
def timer(scripts, env):
for u, s in scripts.items():
print(u, f': `{s}`')
print(f'\t\t{timeit.timeit(s, globals=env):0.4f}s')
Small tup
>>> env['tup'] = tuple(2*(0,) for _ in range(4))
>>> timer(scripts, env)
builtin_sum : `sum(tup, t0)`
0.2976s
chain_from_iterable : `(*fi(tup),)`
0.4653s
nested_comprehension : `[tupl for tuploftupls in tup for tupl in tuploftupls]`
0.7203s
Not small tup
>>> env['tup'] = tuple(10*(0,) for _ in range(50))
>>> timer(scripts, env)
builtin_sum : `sum(tup, t0)`
63.2285s
chain_from_iterable : `(*fi(tup),)`
11.9186s
nested_comprehension : `[tupl for tuploftupls in tup for tupl in tuploftupls]`
20.0901s