Python program to Flatten Nested List to Tuple List


When it is required to flatten a nested list into a tuple list, a method is defined that takes a list as a parameter, and uses the ‘isinstance’ method to check if an element belongs to a specific type. Depending on this, the output is displayed.

Example

Below is a demonstration of the same

def convert_nested_tuple(my_list):
   for elem in my_list:
      if isinstance(elem, list):
         convert_nested_tuple(elem)
      else:
         my_result.append(elem)
   return my_result

my_list = [[[(3, 62)]], [[[(57, 49)]]], [[[[(12, 99)]]]]]

print("The list is :")
print(my_list)

my_result = []
my_result = convert_nested_tuple(my_list)

print("The list is :")
print(my_result)

Output

The list is :
[[[(3, 62)]], [[[(57, 49)]]], [[[[(12, 99)]]]]]
The list is :
[(3, 62), (57, 49), (12, 99)]

Explanation

  • A method named ‘convert_nested_tuple’ is defined that takes a list as a parameter.

  • The list elements are iterated over.

  • The ‘isinstance’ method is used to check if every element in the nested list belong to list type.

  • If yes, the method is called.

  • Otherwise, the element is appended to an empty list.

  • This is returned as result.

  • Outside the method, a nested list of tuple is defined and displayed on the console.

  • An empty list is defined.

  • The method is called by passing the previous list of tuple as a parameter.

  • The output is displayed on the console.

Updated on: 21-Sep-2021

194 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements