Python – Remove particular data type Elements from Tuple

Sometimes, while working with Python tuples, we can have a problem in which we need to remove particular data type elements from tuple. This kind of problem can occur in domains which require data preprocessing. Let’s discuss certain ways in which this task can be performed.

Input : test_tuple = (4, 5, ‘Gfg’, 7.7, ‘Best’), data_type = str
Output : [4, 5, 7.7]

Input : test_tuple = (4, 5, ‘Gfg’, 7.7, ‘Best’), data_type = float
Output : [4, 5, ‘Gfg’, ‘Best’]

Method #1 : Using loop + isinstance()
The combination of above functionalities can be used to solve this problem. In this, we need to iterate for each element and discard the element if it matches the data type, using isinstance().

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Remove particular data type Elements from Tuple
# Using loop + isinstance() 
  
# initializing tuple
test_tuple = (4, 5, 'Gfg', 7.7, 'Best')
  
# printing original tuple
print("The original tuple : " + str(test_tuple))
  
# initializing data type
data_type = int 
  
# Remove particular data type Elements from Tuple
# Using loop + isinstance()
res = []
for ele in test_tuple:
    if not isinstance(ele, data_type):
        res.append(ele)
  
# printing result 
print("The filtered tuple : " + str(res))

chevron_right


Output :



The original tuple : (4, 5, 'Gfg', 7.7, 'Best')
The filtered tuple : ['Gfg', 7.7, 'Best']

 

Method #2 : Using list comprehension + isinstance()
This is yet another way in which this task can be performed. In this, we need to perform similar task using a shorthand by list comprehension.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Remove particular data type Elements from Tuple
# Using list comprehension + isinstance() 
  
# initializing tuple
test_tuple = (4, 5, 'Gfg', 7.7, 'Best')
  
# printing original tuple
print("The original tuple : " + str(test_tuple))
  
# initializing data type
data_type = int 
  
# Remove particular data type Elements from Tuple
# Using list comprehension + isinstance() 
res = [ele for ele in test_tuple if not isinstance(ele, data_type)]
  
# printing result 
print("The filtered tuple : " + str(res))

chevron_right


Output :

The original tuple : (4, 5, 'Gfg', 7.7, 'Best')
The filtered tuple : ['Gfg', 7.7, 'Best']



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.