
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Filter Tuples with Integers in Python
When it is required to filter tuple with integers, a simple iteration and the ‘not’ operator and the ‘isinstance’ method is used.
Example
Below is a demonstration of the same −
my_tuple = [(14, 25, "Python"), (5, 6), (3, ), ("cool", )] print("The tuple is :") print(my_tuple) my_result = [] for sub in my_tuple: temp = True for element in sub: if not isinstance(element, int): temp = False break if temp : my_result.append(sub) print("The result is :") print(my_result)
Output
The tuple is : [(14, 25, 'Python'), (5, 6), (3,), ('cool',)] The result is : [(5, 6), (3,)]
Explanation
A list of tuple is defined and is displayed on the console.
An empty list is created.
The list is iterated over, and the ‘isinstance’ method is used to see if the element belong to integer type.
If yes, a Boolean value is assigned to ‘False’.
The control breaks out of the loop.
Depending on the value of Boolean value, the element is appended to the empty list.
This is the output that is displayed on the console.
Advertisements