How to convert the following tuple:
from:
(('aa', 'bb', 'cc'), 'dd')
to:
('aa', 'bb', 'cc', 'dd')
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.
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.
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.
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.
a = (1, 2)
b = (3, 4)
x = a + b
print(x)
Out:
(1, 2, 3, 4)
>>> tuple(j for i in (('aa', 'bb', 'cc'), 'dd') for j in (i if isinstance(i, tuple) else (i,)))
('aa', 'bb', 'cc', 'dd')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With