Q:

Python | Flatten Nested Tuples

belongs to collection: Python Tuple Programs

0

Example:

tuple = ("python", "includehelp", 43, 54.23)

Nested Tuples are tuples that have tuples as their elements.

Example:

nestedTuple = ((1, 7), (3, 6), (2, 5))

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Flattening Nested Tuples

To solve the problem is by finding all the nested tuples in each tuple element of the container. And then flatten it to a normal tuple with all elements of the nested as individual elements.

In the Python programming language, we will use a recursive approach to find the nested tuples for each instance of the container collection. For checking whether the tuple has nested tuples as its elements, we will be using the instance() method. And then for each nested tuple instance, we will flatten it to the tuple.

# Python program to flatten Nested Tuple

# Recursive function to flatten nested tuples
def flattenRec(nestedTuple):
	if isinstance(nestedTuple, tuple) and len(nestedTuple) == 2 and not isinstance(nestedTuple[0], tuple):
		flattenTuple = [nestedTuple]
		return tuple(flattenTuple)
	flattenTuple = []
	for sub in nestedTuple:
		flattenTuple += flattenRec(sub)
	return tuple(flattenTuple)

# Creating and printing nestTuple container
nestedTuple = ((2, 5), ((1, 5), (4, 7)))
print("The original tuple : " + str(nestedTuple))

# Calling flatten method
flattenTuple = flattenRec(nestedTuple)

# printing the flattened tuple 
print("The flattened tuple : " + str(flattenTuple))

Output:

The original tuple : ((2, 5), ((1, 5), (4, 7)))
The flattened tuple : ((2, 5), (1, 5), (4, 7))

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to clear tuple elements... >>
<< Python | Convert List of Lists to Tuple of Tuples...