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
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:
- The outer list comprehension iterates through each tuple in the list
- The inner list comprehension filters elements within each tuple
- The
type(j) != strcondition excludes string elements - 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.
