
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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.
- Related Articles
- Python Program to Flatten a Nested List using Recursion
- Flatten tuple of List to tuple in Python
- 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 How to copy a nested list
- Python program to convert a list of strings with a delimiter to a list of tuple
- Python - Convert given list into nested list
- Flatten given list of dictionaries in Python
- Python program to unique keys count for Value in Tuple List
- Nested list comprehension in python
- Flatten Binary Tree to Linked List in C++
