2

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"?

gbox
  • 809
  • 1
  • 8
  • 22

4 Answers4

3

If you're looking to flatten a general tuple of tuples, you could:

  1. use a list/generator comprehension
flattened_tup = tuple(j for i in tup for j in i)
  1. use itertools
import itertools
flattened_tup = tuple(itertools.chain.from_iterable(tup))
Lucas Ng
  • 671
  • 4
  • 11
2

tup = part1+part2
python adds the objects of tuples behind each other during addition

Xyndra
  • 110
  • 1
  • 11
0

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

Aakash Parsi
  • 93
  • 2
  • 10
  • Using a builtin as a variable name is almost universally a bad idea. Also the variable name `values` is misleading as it is a singular value. – Lucas Ng May 16 '21 at 14:24
0

For the sake of performance, if I had to repeatedly perform such concatenations over small tups, 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
keepAlive
  • 6,369
  • 5
  • 24
  • 39