Python program to remove nested records from tuple

In this program, we are given a nested tuple i.e., a tuple consisting of nested tuples inside it. We need to create a python program to remove nested records from tuples.
Submitted by Shivang Yadav, on November 22, 2021

In Python, we need to check whether data is in proper form or not. We need to cleanse data before working with it. Here, we need to check and remove nested records from the given tuple. 

Before going further with the problem, let's recap some basic topics that will help in understanding the solution.

Python programming language is a high-level and object-oriented programming language. Python is an easy to learn, powerful high-level programming language. It has a simple but effective approach to object-oriented programming.

Tuples in Python is a collection of items similar to list with the difference that it is ordered and immutable.

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.

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)

Python Tuple Programs »



Related Programs




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.