Remove nested records from tuple in Python


When it is required to remove nested record/tuples from a tuple of tuple, a simple loop and the 'isinstance' method and the enumerate method can be used.

The enumerate method adds a counter to the given iterable, and returns it. The 'isinstance' method checks to see if a given parameter belong to a specific data type or not.

Below is a demonstration of the same −

Example

Live Demo

tuple_1 = (11, 23, (41, 25, 22), 19)

print("The tuple is : ")
print(tuple_1)

my_result = tuple()
for count, elem in enumerate(tuple_1):
   if not isinstance(elem, tuple):
      my_result = my_result + (elem, )

print("Elements after removing the nested tuple is : ")
print(my_result)

Output

The tuple is :
(11, 23, (41, 25, 22), 19)
Elements after removing the nested tuple is :
(11, 23, 19)

Explanation

  • A tuple is defined, and is displayed on the console.
  • Another empty tuple is defined.
  • The first tuple is enumerated, and iterated over.
  • If the element inside the tuple isn't an instance of a specific type, that element is added to the empty list.
  • This operation is assigned to a variable.
  • It is displayed as the output on the console.

Updated on: 11-Mar-2021

223 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements