Python - Flatten Nested Tuples
Last Updated :
10 May, 2023
Sometimes, while working with Python Tuples, we can have a problem in which we need to perform flattening of tuples, which can be nested and undesired. This can have application across many domains such as Data Science and web development. Let's discuss certain way in which this task can be performed.
Input : test_tuple = ((4, 7), ((4, 5), ((6, 7), (7, 6))))
Output : ((4, 7), (4, 5), (6, 7), (7, 6))
Input : test_tuple = ((4, 7), (5, 7), (1, 3))
Output : ((4, 7), (5, 7), (1, 3))
Method 1: Using recursion + isinstance() The combination of above functionalities can help us achieve solution to this problem. In this we use recursion to perform the task of digging into each tuple for inner tuples, and for decision of flattening, isinstance() is used depending upon tuple container or primitive data.
Step-by-step approach :
- Define a function flatten that takes a nested tuple as input.
- If the input tuple is a tuple of length 2 and the first element is not a tuple, wrap it in a tuple and return it.
- If the input tuple is not a tuple of length 2, or if the first element is a tuple, continue to the next step.
- Create an empty list res to store the flattened tuple.
- Iterate over each element sub in the input tuple.
- If sub is a tuple, recursively call flatten on sub and add the flattened tuple to res.
- If sub is not a tuple, add it to res.
- Convert res to a tuple and return it.
- Initialize a nested tuple test_tuple.
- Print the original tuple to the console.
- Call flatten on test_tuple and store the result in res.
- Print the flattened tuple to the console.
Python3
# Python3 code to demonstrate working of
# Flatten Nested Tuples
# Using recursion + isinstance()
# helper function
def flatten(test_tuple):
if isinstance(test_tuple, tuple) and len(test_tuple) == 2 and not isinstance(test_tuple[0], tuple):
res = [test_tuple]
return tuple(res)
res = []
for sub in test_tuple:
res += flatten(sub)
return tuple(res)
# initializing tuple
test_tuple = ((4, 5), ((4, 7), (8, 9), (10, 11)), (((9, 10), (3, 4))))
# printing original tuple
print("The original tuple : " + str(test_tuple))
# Flatten Nested Tuples
# Using recursion + isinstance()
res = flatten(test_tuple)
# printing result
print("The flattened tuple : " + str(res))
Output : The original tuple : ((4, 5), ((4, 7), (8, 9), (10, 11)), ((9, 10), (3, 4)))
The flattened tuple : ((4, 5), (4, 7), (8, 9), (10, 11), (9, 10), (3, 4))
Time complexity: The time complexity of the function is O(N), where N is the total number of elements in the input nested tuple.
Auxiliary space: The auxiliary space used by the function is also O(N), where N is the total number of elements in the input nested tuple
Method 2: itertools.chain.from_iterable()
This program uses itertools.chain.from_iterable() method to flatten the nested tuple test_tuple and returns a new flattened tuple.
Python3
import itertools
# initializing tuple
test_tuple = ((4, 5), ((4, 7), (8, 9), (10, 11)), (((9, 10), (3, 4))))
# printing original tuple
print("The original tuple : " + str(test_tuple))
# Flatten Nested Tuples using itertools.chain.from_iterable()
res = tuple(itertools.chain.from_iterable(test_tuple))
# printing result
print("The flattened tuple : " + str(res))
OutputThe original tuple : ((4, 5), ((4, 7), (8, 9), (10, 11)), ((9, 10), (3, 4)))
The flattened tuple : (4, 5, (4, 7), (8, 9), (10, 11), (9, 10), (3, 4))
Time complexity: O(n), where n is the total number of elements in the nested tuple.
Space complexity: O(n), since the output tuple contains n elements.
Method 3: use a generator function that iterates over the elements of the input tuple and yields non-tuple values, and recursively calls itself on tuple values.
Here's how the flatten_tuples function works:
- It iterates over the elements of the input tuple t.
- If the current element x is a tuple, it recursively calls flatten_tuples on x using the yield from statement.
- If the current element x is not a tuple, it yields it to the calling function.
Python3
def flatten_tuples(t):
for x in t:
if isinstance(x, tuple):
yield from flatten_tuples(x)
else:
yield x
# initializing tuple
test_tuple = ((4, 5), ((4, 7), (8, 9), (10, 11)), (((9, 10), (3, 4))))
# printing original tuple
print("The original tuple : " + str(test_tuple))
# Flatten Nested Tuples
# Using generator function
res = tuple(flatten_tuples(test_tuple))
# printing result
print("The flattened tuple : " + str(res))
OutputThe original tuple : ((4, 5), ((4, 7), (8, 9), (10, 11)), ((9, 10), (3, 4)))
The flattened tuple : (4, 5, 4, 7, 8, 9, 10, 11, 9, 10, 3, 4)
This approach has a time complexity of O(n), where n is the total number of elements in the input tuple, since each element is visited once.
The auxiliary space is O(d), where d is the depth of the nested tuples, since the recursion depth is bounded by the depth of the nested tuples.
Method 4: using the reduce() function from the functools module
- The flatten_tuple() function takes a nested tuple as input and returns a flattened tuple.
- The reducer() function is a helper function that is used in the reduce() function. It takes two arguments: an accumulator (acc) and a value (val). If the value is a tuple, it recursively calls flatten_tuple() on the tuple and concatenates the result to the accumulator. If the value is not a tuple, it appends the value to the accumulator.
- The reduce() function applies the reducer() function to each element of the nested tuple and reduces it to a single flattened tuple.
- Finally, the flattened tuple is returned as the result.
Python3
from functools import reduce
def flatten_tuple(nested_tuple):
def reducer(acc, val):
if isinstance(val, tuple):
return acc + flatten_tuple(val)
else:
return acc + (val,)
return reduce(reducer, nested_tuple, ())
# initializing tuple
test_tuple = ((4, 5), ((4, 7), (8, 9), (10, 11)), (((9, 10), (3, 4))))
# printing original tuple
print("The original tuple : " + str(test_tuple))
# flatten nested tuples using reduce() function
res = flatten_tuple(test_tuple)
# printing result
print("The flattened tuple : " + str(res))
OutputThe original tuple : ((4, 5), ((4, 7), (8, 9), (10, 11)), ((9, 10), (3, 4)))
The flattened tuple : (4, 5, 4, 7, 8, 9, 10, 11, 9, 10, 3, 4)
Time Complexity: O(n), where n is the total number of elements in the nested tuple, as each element is visited exactly once.
Auxiliary Space: O(n), as the maximum depth of recursion is equal to the maximum nesting level of the tuple.
Method 5: Using a stack
- Create an empty stack and push the given tuple onto it.
- Create an empty list to store the flattened values.
- While the stack is not empty:
a. Pop the top element from the stack.
b. If the popped element is a tuple, push its elements onto the stack.
c. If the popped element is not a tuple, append it to the flattened list. - Return the flattened list.
Python3
def flatten_tuple(nested_tuple):
stack = [nested_tuple]
flattened_list = []
while stack:
top = stack.pop()
if isinstance(top, tuple):
stack.extend(top)
else:
flattened_list.append(top)
return tuple(flattened_list)
# initializing tuple
test_tuple = ((4, 5), ((4, 7), (8, 9), (10, 11)), (((9, 10), (3, 4))))
# printing original tuple
print("The original tuple : " + str(test_tuple))
# flatten nested tuples using stack
res = flatten_tuple(test_tuple)
# printing result
print("The flattened tuple : " + str(res))
OutputThe original tuple : ((4, 5), ((4, 7), (8, 9), (10, 11)), ((9, 10), (3, 4)))
The flattened tuple : (4, 3, 10, 9, 11, 10, 9, 8, 7, 4, 5, 4)
Time complexity: O(n) - where n is the total number of elements in the nested tuple.
Auxiliary space: O(n) - where n is the total number of elements in the nested tuple.
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read