Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge two tuples in Python?

How to convert the following tuple:

from:

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

to:

('aa', 'bb', 'cc', 'dd')
like image 812
Cory Avatar asked Feb 07 '13 06:02

Cory


People also ask

Can 2 tuples be added?

You can combine tuples to form a new tuple. The addition operation simply performs a concatenation with tuples. You can only add or combine same data types. Thus combining a tuple and a list gives you an error.

Can we concatenate tuple and list?

The Python "TypeError: can only concatenate tuple (not "list") to tuple" occurs when we try to concatenate a tuple and a list. To solve the error, make sure the two values are of type list or of type tuple before concatenating them.

Can we append tuple in Python?

You can concatenate a tuple by adding new items to the beginning or end as previously mentioned; but, if you wish to insert a new item at any location, you must convert the tuple to a list.


3 Answers

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.

like image 166
Volatility Avatar answered Oct 17 '22 21:10

Volatility


a = (1, 2)
b = (3, 4)

x = a + b

print(x)

Out:

(1, 2, 3, 4)
like image 46
Thirumal Alagu Avatar answered Oct 17 '22 21:10

Thirumal Alagu


>>> tuple(j for i in (('aa', 'bb', 'cc'), 'dd') for j in (i if isinstance(i, tuple) else (i,)))
('aa', 'bb', 'cc', 'dd')
like image 19
John La Rooy Avatar answered Oct 17 '22 22:10

John La Rooy