Removing strings from tuple in Python

When it is required to remove strings from a tuple, the list comprehension and the type() method can be used. This approach allows you to filter out string elements while preserving other data types like integers and floats.

A list can be used to store heterogeneous values (data of any data type like integer, floating point, strings, and so on). A list of tuples contains tuples enclosed in a list.

List comprehension is a shorthand to iterate through the list and perform operations on it. The type() method returns the class of the object passed to it as an argument.

Example

Below is a demonstration of removing strings from tuples ?

my_list = [('Hi', 45, 67), ('There', 45, 32), ('Jane', 59, 13)]

print("The list is :")
print(my_list)

my_result = [tuple([j for j in i if type(j) != str])
             for i in my_list]
print("The list of tuple after removing the string is :")
print(my_result)
The list is :
[('Hi', 45, 67), ('There', 45, 32), ('Jane', 59, 13)]
The list of tuple after removing the string is :
[(45, 67), (45, 32), (59, 13)]

Using isinstance() for Better Type Checking

A more Pythonic approach uses isinstance() instead of type() ?

my_list = [('Hello', 42, 3.14), ('World', 100, 2.5)]

print("Original list:")
print(my_list)

# Using isinstance() for type checking
result = [tuple(item for item in t if not isinstance(item, str))
          for t in my_list]

print("After removing strings:")
print(result)
Original list:
[('Hello', 42, 3.14), ('World', 100, 2.5)]
After removing strings:
[(42, 3.14), (100, 2.5)]

How It Works

The solution works in these steps:

  1. The outer list comprehension iterates through each tuple in the list
  2. The inner list comprehension filters elements within each tuple
  3. The type(j) != str condition excludes string elements
  4. The filtered elements are converted back to a tuple using tuple()

Comparison

Method Advantage Best For
type() Exact type matching Simple type filtering
isinstance() Handles inheritance More robust type checking

Conclusion

Use list comprehension with type() or isinstance() to remove strings from tuples. The isinstance() method is generally preferred for more robust type checking in Python applications.

Updated on: 2026-03-25T17:41:23+05:30

741 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements