Q:

Python program to remove nested records from tuple

0

Example:

tuple = ("python", "includehelp", 43, 54.23)

Removing nested records from tuple

We need to remove all the nested records from the given tuple. And for this, we need to iterate all elements of the tuple and check if it's a record. And eliminate the record from the tuple.

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

Output:
(3, 6, 1, 5)

In Python, we can perform the task in multiple ways using one of the multiple methods that are present in the function.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Method 1:

One method to solve the problem is by iterating over all elements of the tuple by using enumerate() method and checking if it is a tuple or not using isinstance() method. And for all elements that are not nested records, create a new tuple.

# Python Program to remove nested records from tuple

# Initializing and printing the tuple
myTuple = (3, 6, 1, (9, 8), 5)
print("The elements of tuple are " + str(myTuple))
  
# Remove nested records form tuple
linearTuple = tuple()
for count, val in enumerate(myTuple):
    if not isinstance(val, tuple):
        linearTuple = linearTuple + (val, )
  
# Printing converted tuple
print("The elements of tuple after removal nested records are " + str(linearTuple))

Output:

The elements of tuple are (3, 6, 1, (9, 8), 5)
The elements of tuple after removal nested records are (3, 6, 1, 5)

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now