Search code examples
pythontuplesunpack

Unpack tuples inside a tuple


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


Solution

  • 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))