Open In App

Python – Remove nested records from tuple

Last Updated : 27 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with records, we can have a problem in which an element of a record is another tuple records and we might have to remove the nested records. This is a problem which does not occur commonly, but having a solution to it is useful. Let’s discuss certain way in which this task can be performed.
 

Method 1: Using loop + isinstance() + enumerate() 
This problem can be solved using the above functionalities. In this, we just loop through the elements using enumerate() to get the index count of it and check the type using isinstance() and recreate the new tuple by checking ignoring tuple records.

Python3




# Python3 code to demonstrate working of
# Remove nested records
# using isinstance() + enumerate() + loop
 
# initialize tuple
test_tup = (1, 5, 7, (4, 6), 10)
 
# printing original tuple
print("The original tuple : " + str(test_tup))
 
# Remove nested records
# using isinstance() + enumerate() + loop
res = tuple()
for count, ele in enumerate(test_tup):
    if not isinstance(ele, tuple):
        res = res + (ele, )
 
# printing result
print("Elements after removal of nested records : " + str(res))


Output

The original tuple : (1, 5, 7, (4, 6), 10)
Elements after removal of nested records : (1, 5, 7, 10)

Time Complexity: O(n), where n is the length of the list test_tup
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list

Method 2 : Using type() method

Python3




# Python3 code to demonstrate working of
# Remove nested records
 
# initialize tuple
test_tup = (1, 5, 7, (4, 6), 10)
 
# printing original tuple
print("The original tuple : " + str(test_tup))
 
# Remove nested records
res=[]
for i in test_tup:
    if not type(i) is tuple:
        res.append(i)
res=tuple(res)
# printing result
print("Elements after removal of nested records : " + str(res))


Output

The original tuple : (1, 5, 7, (4, 6), 10)
Elements after removal of nested records : (1, 5, 7, 10)

Time complexity: O(n), where n is the number of elements in the tuple.

Auxiliary Space: O(n), where n is the number of elements in the tuple.

Method 3 : Using filter()+lambda functions

Python3




# Python3 code to demonstrate working of
# Remove nested records
 
# initialize tuple
test_tup = (1, 5, 7, (4, 6), 10)
 
# printing original tuple
print("The original tuple : " + str(test_tup))
 
# Remove nested records
res = list(filter(lambda x: not isinstance(x, tuple), test_tup))
 
# printing result
print("Elements after removal of nested records : " + str(res))


Output

The original tuple : (1, 5, 7, (4, 6), 10)
Elements after removal of nested records : [1, 5, 7, 10]

Time Complexity:O(N)
Auxiliary Space: O(N)

Method 4: Using list comprehension
 

Python3




# Python3 code to demonstrate working of
# Remove nested records
  
# initialize tuple
test_tup = (1, 5, 7, (4, 6), 10)
  
# printing original tuple
print("The original tuple : " + str(test_tup))
  
# Remove nested records
res = [x for x in test_tup if not isinstance(x, tuple)]
  
# printing result
print("Elements after removal of nested records : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy


Output

The original tuple : (1, 5, 7, (4, 6), 10)
Elements after removal of nested records : [1, 5, 7, 10]

Time Complexity: O(N)
Auxiliary Space: O(N)

Python3




from functools import reduce
test_tup = (1, 5, 7, (4, 6), 10)
# printing original tuple
print("The original tuple : " + str(test_tup))
res = reduce(lambda acc, x: acc + (x,) if not isinstance(x, tuple) else acc, test_tup, ())
print(res)
#This code is contributed by Jyothi pinjala.


Output

The original tuple : (1, 5, 7, (4, 6), 10)
(1, 5, 7, 10)

Time Complexity: O(N)
Auxiliary Space: O(N)

Method 5: Method 5: Using itertools.chain()

Use the itertools.chain() function to flatten the nested tuple and create a new tuple without the inner tuples.

Python3




import itertools
 
test_tup = (1, 5, 7, (4, 6), 10)
print("The original tuple: " + str(test_tup))
 
res = tuple(itertools.chain(*([x] if not isinstance(x, tuple) else x for x in test_tup)))
print(res)


Output

The original tuple: (1, 5, 7, (4, 6), 10)
(1, 5, 7, 4, 6, 10)

Time complexity: O(n), where n is the number of elements in the tuple.
Auxiliary space: O(n), as it creates a new tuple of the same length as the original tuple.

Method 6: using recursion

  • Define a function flatten_tuple that takes a tuple as an argument.
  • Create an empty list result.
  • For each element elem in the input tuple, check if it is a tuple using isinstance(elem, tuple).
  • If elem is not a tuple, append it to the result list.
  • If elem is a tuple, recursively call the flatten_tuple function on it and extend the result list with the flattened tuple.
  • Return the flattened result list as a tuple.

Python3




def flatten_tuple(tup):
    """
    Recursively flatten a tuple of any depth into a single tuple.
 
    Args:
        tup: A tuple to be flattened.
 
    Returns:
        A flattened tuple.
 
    """
    result = []
    for elem in tup:
        if not isinstance(elem, tuple):
            result.append(elem)
        else:
            result.extend(flatten_tuple(elem))
    return tuple(result)
 
# Driver code to test the function
test_tup = (1, 5, 7, (4, 6), 10)
print("The original tuple: " + str(test_tup))
 
# Call the function to flatten the tuple
res = flatten_tuple(test_tup)
 
# Print the flattened tuple
print(res)


Output

The original tuple: (1, 5, 7, (4, 6), 10)
(1, 5, 7, 4, 6, 10)

Time complexity: O(n), where n is the length of given test_tup
Auxiliary space: O(n) since it creates a new list to store the flattened elements. 



Similar Reads

Python - Remove None Nested Records
Sometimes, while working with Python Records, can have problem in which we need to perform the removal of data which have all key's values as None in nested records. This kind of problem can have application in data preprocessing. Lets discuss certain ways in which this task can be performed. Method #1 : Using all() + dictionary comprehension The c
4 min read
Python - Remove all duplicate occurring tuple records
Sometimes, while working with records, we can have a problem of removing those records which occur more than once. This kind of application can occur in web development domain. Let’s discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + set() + count() Initial approach that can be applied is that we can it
6 min read
Python | Nested Records Modulo
Sometimes, while working with records, we can have a problem in which we require to perform index wise remainder 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 : Using zip() + nested generator expression The comb
5 min read
Python - Test for empty Nested Records
Sometimes, while working with Python dictionaries, we can have a problem in which we need to test if a particular dictionary has nested records, and all of them is empty, i.e with no key or no value in case of list. This kind of problem is quite common in data domains such as Data Science. Let's discuss certain way in which this task can be perform
6 min read
Python - Nested Records List from Lists
Sometimes, while working with Python Data, we can have problems in which we have data incoming in different formats. In this, we can receive data as key and value in separate dictionaries and we are required to make values as list of records with a new key. Let's discuss certain ways in which we can convert nested record lists from lists. Nested Li
6 min read
Python | Convert tuple records to single string
Sometimes, while working with data, we can have a problem in which we have tuple records and we need to change it's to comma-separated strings. These can be data regarding names. This kind of problem has its application in the web development domain. Let's discuss certain ways in which this problem can be solved Method #1: Using join() + list compr
6 min read
Python | Intersection in Tuple Records Data
Sometimes, while working with data, we may have a problem in which we require to find the matching records between two lists that we receive. This is a very common problem and records usually occur as a tuple. Let's discuss certain ways in which this problem can be solved. Method #1 : Using list comprehension List comprehension can opt as method to
7 min read
Python | Minimum K records of Nth index in tuple list
Sometimes, while working with data, we can have a problem in which we need to get the minimum of elements filtered by the Nth element of record. This has a very important utility in web development domain. Let’s discuss certain ways in which this task can be performed. Method #1 : Using filter() + lambda + set() + list comprehension The combination
9 min read
Python - Find minimum k records from tuple list
Sometimes, while working with data, we can have a problem in which we have records and we require to find the lowest K scores from it. This kind of application is popular in web development domain. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using sorted() + lambda The combination of above functionality can be used t
6 min read
Python - Prefix tuple records
Sometimes, while working with Python lists, we can have problem in which we need to find all the tuples which begin with a particular tuple record. This kind of problem can find application in data domains. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + zip() + all() The combination of above f
6 min read
Practice Tags :
three90RightbarBannerImg