Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python – Filter Tuples with Integers
When it is required to filter tuples that contain only integers, a simple iteration with the 'not' operator and the 'isinstance' method can be used to check each element's data type.
Example
Below is a demonstration of filtering tuples with integers ?
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,)]
How It Works
The algorithm iterates through each tuple in the list and checks every element:
- For each sub-tuple, a boolean flag
tempis set toTrue - The
isinstance(element, int)method checks if each element is an integer - If any non-integer is found,
tempbecomesFalseand the loop breaks - Only tuples where all elements are integers get added to the result
Using List Comprehension
A more concise approach uses list comprehension with the all() function ?
my_tuple = [(14, 25, "Python"), (5, 6), (3, ), ("cool", )]
print("The tuple is :")
print(my_tuple)
my_result = [sub for sub in my_tuple if all(isinstance(element, int) for element in sub)]
print("The result is :")
print(my_result)
The tuple is :
[(14, 25, 'Python'), (5, 6), (3,), ('cool',)]
The result is :
[(5, 6), (3,)]
Conclusion
Use isinstance() with loops for explicit control, or combine all() with list comprehension for a more concise solution. Both methods effectively filter tuples containing only integer values.
Advertisements
