
- 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
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
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.
- Related Articles
- Python program to Flatten Nested List to Tuple List
- Dictionary to list of tuple conversion in Python
- Python Grouped summation of tuple list¶
- Grouped summation of tuple list in Python
- Python – Cross Pairing in Tuple List
- Python - Ways to iterate tuple list of lists
- Why python returns tuple in list instead of list in list?
- Summation of list as tuple attribute in Python
- Maximum element in tuple list in Python
- Python - Join tuple elements in a list
- List vs tuple vs dictionary in Python
- Difference Between List and Tuple in Python
- Modifying tuple contents with list in Python
- Python – Concatenate Rear elements in Tuple List
- Extract digits from Tuple list Python
