Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Flatten Nested Keys
Next article icon

Python – Flatten Nested Tuples

Last Updated : 10 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 :

  1. Define a function flatten that takes a nested tuple as input.
  2. 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.
  3. If the input tuple is not a tuple of length 2, or if the first element is a tuple, continue to the next step.
  4. Create an empty list res to store the flattened tuple.
  5. Iterate over each element sub in the input tuple.
  6. If sub is a tuple, recursively call flatten on sub and add the flattened tuple to res.
  7. If sub is not a tuple, add it to res.
  8. Convert res to a tuple and return it.
  9. Initialize a nested tuple test_tuple.
  10. Print the original tuple to the console.
  11. Call flatten on test_tuple and store the result in res.
  12. 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))
 
 
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: 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:

  1. It iterates over the elements of the input tuple t.
  2. If the current element x is a tuple, it recursively calls flatten_tuples on x using the yield from statement.
  3. 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))
 
 
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)

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

  1. The flatten_tuple() function takes a nested tuple as input and returns a flattened tuple.
  2. 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.
  3. The reduce() function applies the reducer() function to each element of the nested tuple and reduces it to a single flattened tuple.
  4. 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))
 
 
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: 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))
 
 
Output
The 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.



Next Article
Python - Flatten Nested Keys
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python Nested-Tuples
  • Python tuple-programs
Practice Tags :
  • python

Similar Reads

  • Python - Maximize Nested Tuples
    Sometimes, while working with records, we can have a problem in which we require to perform an index-wise maximum of tuple elements. This can get complicated with tuple elements being tuples and inner elements again being tuples. Let’s discuss certain ways in which this problem can be solved. Method
    8 min read
  • Addition in Nested Tuples - Python
    Sometimes, while working with records, we can have a problem in which we require to perform index wise addition of tuple elements. This can get complicated with tuple elements to be tuple and inner elements again be tuple. Let's discuss certain ways in which this problem can be solved. Method #1: Us
    6 min read
  • Python - Flatten Nested Keys
    Sometimes, while working with Python data, we can have a problem in which we need to perform the flattening of certain keys in nested list records. This kind of problem occurs while data preprocessing. Let us discuss certain ways in which this task can be performed. Method #1: Using loopThis is a br
    10 min read
  • Python Tuple - len() Method
    While working with tuples many times we need to find the length of the tuple, and, instead of counting the number of elements with loops, we can also use Python len(). We will learn about the len() method used for tuples in Python. Example: [GFGTABS] Python3 Tuple =( 1, 0, 4, 2, 5, 6, 7, 5) print(le
    2 min read
  • Python | Flatten Tuples List to String
    Sometimes, while working with data, we can have a problem in which we need to perform interconversion of data. In this, we can have a problem of converting tuples list to a single String. Let's discuss certain ways in which this task can be performed. Method #1: Using list comprehension + join() The
    7 min read
  • Flatten tuple of List to tuple - Python
    The task of flattening a tuple of lists to a tuple in Python involves extracting and combining elements from multiple lists within a tuple into a single flattened tuple. For example, given tup = ([5, 6], [6, 7, 8, 9], [3]), the goal is to flatten it into (5, 6, 6, 7, 8, 9, 3). Using itertools.chain(
    3 min read
  • Python - Extend consecutive tuples
    Given list of tuples, join consecutive tuples. Input : test_list = [(3, 5, 6, 7), (3, 2, 4, 3), (9, 4), (2, 3, 2)] Output : [(3, 5, 6, 7, 3, 2, 4, 3), (3, 2, 4, 3, 9, 4), (9, 4, 2, 3, 2)] Explanation : Elements joined with their consecutive tuples. Input : test_list = [(3, 5, 6, 7), (3, 2, 4, 3)] Ou
    3 min read
  • Unpacking Nested Tuples-Python
    The task of unpacking nested tuples in Python involves iterating through a list of tuples, extracting values from both the outer and inner tuples and restructuring them into a flattened format. For example, a = [(4, (5, 'Gfg')), (7, (8, 6))] becomes [(4, 5, 'Gfg'), (7, 8, 6)]. Using list comprehensi
    3 min read
  • Python Access Tuple Item
    In Python, a tuple is a collection of ordered, immutable elements. Accessing the items in a tuple is easy and in this article, we'll explore how to access tuple elements in python using different methods. Access Tuple Items by IndexJust like lists, tuples are indexed in Python. The indexing starts f
    2 min read
  • Python program to Flatten Nested List to Tuple List
    Given a list of tuples with each tuple wrapped around multiple lists, our task is to write a Python program to flatten the container to a list of tuples. Input : test_list = [[[(4, 6)]], [[[(7, 4)]]], [[[[(10, 3)]]]]]Output : [(4, 6), (7, 4), (10, 3)]Explanation : The surrounded lists are omitted ar
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences