Flatten tuple of List to tuple in Python


When it is required to flatten tuple of a list to tuple, a method is defined, that takes input as tuple.

The tuple is iterated over, and the same method is called on it over and over again until the result is obtained.

Below is the demonstration of the same −

Example

 Live Demo

def flatten_tuple(my_tuple):

   if isinstance(my_tuple, tuple) and len(my_tuple) == 2 and not isinstance(my_tuple[0], tuple):
      my_result = [my_tuple]
      return tuple(my_result)

   my_result = []
   for sub in my_tuple:
      my_result += flatten_tuple(sub)
   return tuple(my_result)

my_tuple = ((35, 46), ((67, 70), (8, 11), (10, 111)), (((21, 12), (3, 4))))

print("The tuple is : " )
print(my_tuple)

my_result = flatten_tuple(my_tuple)

print("The flattened tuple is : ")
print(my_result)

Output

The tuple is :
((35, 46), ((67, 70), (8, 11), (10, 111)), ((21, 12), (3, 4)))
The flattened tuple is :
((35, 46), (67, 70), (8, 11), (10, 111), (21, 12), (3, 4))

Explanation

  • A method named ‘flatten_tuple’ is defined, that takes a tuple as parameter.

  • It checks if the tuple is actually a tuple, and whether the length of tuple is equal to 2.

  • If so, it is returned as output.

  • Further, an empty list is defined.

  • The tuple is again iterated over, and elements from flattened tuple are added to this list.

  • It is returned as final output.

  • A tuple of tuple is defined outside the method and displayed on the console.

  • The method is called by passing this tuple of tuple as parameter.

  • The output is displayed on the console.

Updated on: 19-Apr-2021

215 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements