Open In App

Python – Extract Even elements in Nested Mixed Tuple

Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python tuples, we can have a problem in which we need to get all the even elements from the tuple. The tuples can be nested or mixed. This kind of problem can occur in data domains. Let’s discuss certain ways in which this task can be performed.

Input : test_tuple = (5, (7, 6, (2, (4, )))) 
Output : ((6, (2, (4, ))), )

Input : test_tuple = (5, (8, 6, (2, (4, 8)))) 
Output : ((8, 6, (2, (4, 8))), ) 
 

Method #1 : Using recursion + isinstance() + loop 
This is one of the ways in which this task can be performed. In this, we perform the task of getting the element instance to be integer using isinstance(), and the function is recursed once tuple is encountered.

Python3




# Python3 code to demonstrate working of
# Extract Even elements in Nested Mixed Tuple
# Using recursion + isinstance() + loop
 
# helper_fnc
def even_ele(test_tuple, even_fnc):
    res = tuple()
    for ele in test_tuple:
        if isinstance(ele, tuple):
            res += (even_ele(ele, even_fnc), )
        elif even_fnc(ele):
            res += (ele, )
    return res
 
# initializing tuples
test_tuple = (4, 5, (7, 6, (2, 4)), 6, 8)
 
# printing original tuple
print("The original tuple : " + str(test_tuple))
 
# Extract Even elements in Nested Mixed Tuple
# Using recursion + isinstance() + loop
res = even_ele(test_tuple, lambda x: x % 2 == 0)
 
# printing result
print("Even elements of tuple : " + str(res))


Output : 

The original tuple : (4, 5, (7, 6, (2, 4)), 6, 8)
Even elements of tuple : (4, (6, (2, 4)), 6, 8)

 

Method #2 : Using recursion + isinstance() + generator expression 
This method performs this task in a similar manner as the above method. The difference is just that it is shorthand to the above method, does the job in one line using generator expression.

Python3




# Python3 code to demonstrate working of
# Extract Even elements in Nested Mixed Tuple
# Using recursion + isinstance() + generator expression
 
# helper_fnc
def even_ele(test_tuple, even_fnc):
    return tuple(even_ele(ele, even_fnc) if isinstance(ele, tuple) else ele
    for ele in test_tuple if isinstance(ele, tuple) or even_fnc(ele))
 
# initializing tuples
test_tuple = (4, 5, (7, 6, (2, 4)), 6, 8)
 
# printing original tuple
print("The original tuple : " + str(test_tuple))
 
# Extract Even elements in Nested Mixed Tuple
# Using recursion + isinstance() + generator expression
res = even_ele(test_tuple, lambda x: x % 2 == 0)
 
# printing result
print("Even elements of tuple : " + str(res))


Output : 

The original tuple : (4, 5, (7, 6, (2, 4)), 6, 8)
Even elements of tuple : (4, (6, (2, 4)), 6, 8)

 

Method #3: Using for loop

Here’s a step-by-step algorithm 

  1. Create an empty list called result to hold the even integers found in the tuple.
  2. For each element item in the input tuple t:
    a. If item is a tuple, recursively call the extract_even_elements function with item as input.
    b. If item is an even integer, append it to the result list.
  3. Return the result list as a tuple

Python3




def extract_even_elements(t):
    result = []
    for item in t:
        if isinstance(item, tuple):
            result.append(extract_even_elements(item))
        elif isinstance(item, int) and item % 2 == 0:
            result.append(item)
    return tuple(result)
 
# Example usage
test_tuple = (4, 5, (7, 6, (2, 4)), 6, 8)
result = extract_even_elements(test_tuple)
# printing original tuple
print("The original tuple : " + str(test_tuple))
print("Even elements of tuple : " + str(result))
#This code is contributed by Vinay Pinjala.


Output

The original tuple : (4, 5, (7, 6, (2, 4)), 6, 8)
Even elements of tuple : (4, (6, (2, 4)), 6, 8)

Time Complexity: O(n)

Auxiliary Space: O(n)

The time complexity of this function depends on the size of the input tuple and the number of nested tuples. In the worst case, the function would need to traverse every element of the input tuple and any nested tuples, so the time complexity is O(n), where n is the total number of elements in the input tuple.

The space complexity of this function depends on the depth and structure of the nested tuples in the input. At each level of recursion, a new list is created to hold the even integers found within that level of the tuple, and the function continues to call itself until it reaches the end of the nested tuple structure. Therefore, the space complexity is also O(n), where n is the total number of elements in the input tuple.



Last Updated : 24 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads