56

How to convert the following tuple:

from:

(('aa', 'bb', 'cc'), 'dd')

to:

('aa', 'bb', 'cc', 'dd')
questionto42
  • 7,175
  • 4
  • 57
  • 90
Cory
  • 14,865
  • 24
  • 57
  • 72

5 Answers5

53
l = (('aa', 'bb', 'cc'), 'dd')
l = l[0] + (l[1],)

This will work for your situation, however John La Rooy's solution is better for general cases.

MichaelChirico
  • 33,841
  • 14
  • 113
  • 198
Volatility
  • 31,232
  • 10
  • 80
  • 89
  • I want to achieve the following : `a , b = (12 , 21) , (1,2)` . I want to get a third tuple `c = ( (12,21), (1,2) ) ` .How to do this? – Jdeep Jul 13 '20 at 15:36
46
a = (1, 2)
b = (3, 4)

x = a + b

print(x)

Out:

(1, 2, 3, 4)
Geeocode
  • 5,705
  • 3
  • 20
  • 34
Thirumal Alagu
  • 611
  • 5
  • 10
  • 3
    NB: This answers the title of the question, but not its body. The title of the question should have been "How to destack nested tuples" instead. – scottclowe Feb 18 '20 at 04:05
19
>>> tuple(j for i in (('aa', 'bb', 'cc'), 'dd') for j in (i if isinstance(i, tuple) else (i,)))
('aa', 'bb', 'cc', 'dd')
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
  • `def merge_tuples(*t): return tuple(j for i in (t) for j in (i if isinstance(i, tuple) else (i,)))` to make it more generic. – komodovaran_ Aug 21 '19 at 11:56
8
x = (('aa', 'bb', 'cc'), 'dd')
tuple(list(x[0]) + [x[1]])
xvorsx
  • 2,322
  • 2
  • 18
  • 19
3
l = (('aa', 'bb', 'cc'), 'dd')

You can simply do:

(*l[0], l[1])

Result:

('aa', 'bb', 'cc', 'dd')
Luna
  • 31
  • 2