- 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
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 −
def flatten_tuple(my_tuple): if isinstance(my_tuple, tuple) and len(my_tuple) == 2 and not isinstance(my_tuple, 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)
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))
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.
- Python program to Flatten Nested List to Tuple List
- Dictionary to list of tuple conversion in Python
- Grouped summation of tuple list in Python
- Python - Ways to iterate tuple list of lists
- Python Grouped summation of tuple list¶
- Summation of list as tuple attribute in Python
- Why python returns tuple in list instead of list in list?
- Extract digits from Tuple list Python
- Maximum element in tuple list in Python
- Raise elements of tuple as power to another tuple in Python
- List vs tuple vs dictionary in Python
- Python - Join tuple elements in a list
- Difference Between List and Tuple in Python
- Modifying tuple contents with list in Python
- Python – Cross Pairing in Tuple List