- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
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)
The list is : [[[(3, 62)]], [[[(57, 49)]]], [[[[(12, 99)]]]]] The list is : [(3, 62), (57, 49), (12, 99)]
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.
- Flatten tuple of List to tuple in Python
- Python Program to Flatten a Nested List using Recursion
- Flatten Nested List Iterator in Python
- Python Program to Flatten a List without using Recursion
- Python - Ways to flatten a 2D list
- Flatten Tuples List to String in Python
- Python - Convert List to custom overlapping nested list
- How to flatten a shallow list in Python?
- Python - Convert given list into nested list
- Flatten given list of dictionaries in Python
- Python How to copy a nested list
- Nested list comprehension in python
- Flatten Binary Tree to Linked List in C++
- How to flatten a list using LINQ C#?
- Python program to convert a list of strings with a delimiter to a list of tuple