How to flatten tuple of list to tuple in Python

In this tutorial, we will be learning the steps to be followed in order to flatten tuple of list to tuple in Python.

We will be using sum() function (with empty list as its argument) to combine the list inside the tuple and then convert the generated list into a tuple.

We create a tuple with random list elements.

_tuple = ([1,2], [1, 2, 3, 4], [1,2,3])

We use the sum() function (with empty list as its argument) to combine the list inside the tuple

final_tuple=sum(_tuple, []) # returns list

Convert list to tuple

Convert the generated list into a tuple

tuple(final_tuple)

Complete Code: Flatten tuple of list to tuple in Python

Here is the complete code for this problem

# Initializing a tuple
_tuple = ([1,2], [1, 2, 3, 4], [1,2,3])

# Using sum()
final_tuple=sum(_tuple, [])  # returns list

#Convert list to tuple
tuple(final_tuple)

# printing result
print("The Final Flattened Tuple : " + str(final_tuple))

Output

flatten tuple of list to tuple in Python

Leave a Reply

Your email address will not be published. Required fields are marked *