- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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.
Advertisements