Search code examples
pythonnestedtuplesconcatenation

Concatenating nested tuples


Given two variables

A = (2, 3)
B = (1, 4), (5, 8)

what is the simplest way to concatenate the two into a result variable C, so that:

C = ((2, 3), (1, 4), (5, 8))

Note that simply calling:

C = A + B 

results in:

C = (2, 3, (1, 4), (5, 8))

which is not the desired result.

Further, note that tuples are preferred in the place of lists so that A, B and C can be used elsewhere as dictionary keys.


Solution

  • I'd say that you probably meant the A tuple to be a nested tuple as well:

    >>> A = ((2, 3),)
    >>> A + ((1,4), (5,8))
    ((2, 3), (1, 4), (5, 8))