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 temp is set to True
  • The isinstance(element, int) method checks if each element is an integer
  • If any non-integer is found, temp becomes False and 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.

Updated on: 2026-03-26T01:18:34+05:30

250 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements