Python | Flatten Nested Tuples

In this program, we have a tuple of tuples (Nested Tuples). We need to create a Python program that will Flatten Nested Tuples.
Submitted by Shivang Yadav, on October 31, 2021

Flattening of Collections is a very important part of working with structures in any programming language. In this program, we will be learning about a method to perform the fattening task on tuple i.e. we will be flattening nested tuples in Python.

Input:
((2, 5, 9), (1, 8, 7), (3, ((5, 6), (2, 3))))

Output:
((2, 5, 9), (1, 8, 7), (3), (5, 6), (2, 3))

Before going further with the problem, let's recap some basic topics that will help in understanding the solution.

Python programming language is a high-level and object-oriented programming language. Python is an easy to learn, powerful high-level programming language. It has a simple but effective approach to object-oriented programming.

Tuples in Python is a collection of items similar to list with the difference that it is ordered and immutable.

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))

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))

Python Tuple Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.