Python - Remove particular data type Elements from Tuple
Last Updated :
17 Apr, 2023
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().
Python3
# 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))
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.
Python3
# 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))
Output : The original tuple : (4, 5, 'Gfg', 7.7, 'Best')
The filtered tuple : ['Gfg', 7.7, 'Best']
Method #3: Using type() method.type() method returns the data type of variable.Check the type of variable in tuple, if it doesn't matches the given type append them to the output list and display the list
Python3
# Python3 code to demonstrate working of
# Remove particular data type Elements from Tuple
# 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
res=[]
for i in test_tuple:
if(not (type(i) is data_type)):
res.append(i)
# printing result
print("The filtered tuple : " + str(res))
OutputThe original tuple : (4, 5, 'Gfg', 7.7, 'Best')
The filtered tuple : ['Gfg', 7.7, 'Best']
The time complexity of this code is O(n), where n is the length of the input tuple.
The space complexity of this code is also O(n), because we are creating a new list, res, that can potentially store up to n elements, where n is the length of the input tuple.
Method #4: Using filter()
Python3
# 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 filter
res = list(filter(lambda ele: not isinstance(ele, data_type), test_tuple))
# printing result
print("The filtered tuple : " + str(res))
#This code is contributed by Vinay Pinjala.
OutputThe original tuple : (4, 5, 'Gfg', 7.7, 'Best')
The filtered tuple : ['Gfg', 7.7, 'Best']
Time complexity: O(n)
Space complexity : O(n)
Method#5: Using Recursive method.
Algorithm:
- If the input tuple is empty, return an empty tuple.
- Otherwise, split the tuple into the head (first element) and tail (remaining elements).
- If the head element is of the specified data type, recursively call the function on the tail of the tuple.
- Otherwise, include the head element in the result tuple, and recursively call the function on the tail of the tuple.
- Repeat steps 2-4 until the entire tuple has been processed.
- Return the resulting tuple with all elements of the specified data type removed.
Python3
def remove_data_type(tup, data_type):
if not tup:
return ()
head, *tail = tup
if isinstance(head, data_type):
return remove_data_type(tail, data_type)
return (head,) + remove_data_type(tail, data_type)
# 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 Recursive method
res = list(remove_data_type(test_tuple, data_type))
# printing result
print("The filtered tuple : " + str(res))
#This code is contributed by Tvsk.
OutputThe original tuple : (4, 5, 'Gfg', 7.7, 'Best')
The filtered tuple : ['Gfg', 7.7, 'Best']
The time complexity of this function is O(n), where n is the length of the input tuple. This is because the function recursively processes each element of the tuple exactly once, resulting in a linear time complexity.
The space complexity of this function is also O(n), due to the recursive calls that are made on the tail of the tuple. Each recursive call creates a new tuple object that contains a subset of the original tuple, resulting in a space complexity that scales linearly with the size of the input tuple. However, note that the final output tuple is not created until all recursive calls have returned, so the space complexity of the function does not include the space required for the final output tuple.
Method#6:Using reduce() and lambda function:
Algorithm :
- Import the reduce() function from the functools module.
- Define the input tuple and the data type to be removed.
- Use the reduce() function to iterate through the input tuple and create a new tuple containing only the elements that are not of the specified data type.
- Convert the resulting tuple to a list.
- Print the final list.
Python3
from functools import reduce
test_tuple = (4, 5, 'Gfg', 7.7, 'Best')
data_type = int
# printing original tuple
print("The original tuple : " + str(test_tuple))
res = reduce(lambda x, y: x + (y,) if not isinstance(y, data_type) else x, test_tuple, ())
res = list(res)
# printing result
print("The filtered tuple : " + str(res))
#This code is contributed by Jyothi pinjala.
OutputThe original tuple : (4, 5, 'Gfg', 7.7, 'Best')
The filtered tuple : ['Gfg', 7.7, 'Best']
The time complexity: O(n), where n is the length of the input tuple. This is because the reduce() function iterates through each element in the tuple exactly once.
The Auxiliary space: O(n), because a new tuple is created to hold the filtered elements, and then this tuple is converted to a list.
Similar Reads
Python | Get tuple element data types
Tuples can be a collection of various data types, and unlike simpler data types, conventional methods of getting the type of each element of tuple is not possible. For this we need to have different ways to achieve this task. Let's discuss certain ways in which this task can be performed. Method #1
5 min read
Python - Extract Particular data type rows
Given A Matrix, extract all the rows which have all the elements with particular data type. Input : test_list = [[4, 5, "Hello"], [2, 6, 7], ["g", "f", "g"], [9, 10, 11]], data_type = int Output : [[2, 6, 7], [9, 10, 11]] Explanation : All lists with integer are extracted. Input : test_list = [[4, 5
3 min read
Python - Filter tuple with all same elements
Given List of tuples, filter tuples that have same values. Input : test_list = [(5, 6, 5, 5), (6, 6, 6), (9, 10)] Output : [(6, 6, 6)] Explanation : 1 tuple with same elements. Input : test_list = [(5, 6, 5, 5), (6, 5, 6), (9, 10)] Output : [] Explanation : No tuple with same elements. Method #1 : U
4 min read
Removing Tuples from a List by First Element Value - Python
In this problem we need to delete tuples based on a specific condition related to their first element. For example: We are given the list data = [("GeeksforGeeks", "Python", 1000), ("CodingForAll", "Java", 1200)] and we need to remove all tuples where the first element is "GeeksforGeeks", the desire
3 min read
Python - Remove given character from first element of Tuple
Given a Tuple list, remove K character from 1st element of the Tuple being String. Input : test_list = [("GF$g!", 5), ("!i$s", 4), ("best!$", 10)], K = '$' Output : [('GFg!', 5), ('!is', 4), ('best!', 10)] Explanation : First element's strings K value removed. Input : test_list = [("GF$g!", 5), ("be
5 min read
Python - Remove Tuples from the List having every element as None
Given a Tuple list, remove all tuples with all None values. Input : test_list = [(None, 2), (None, None), (3, 4), (12, 3), (None, )] Output : [(None, 2), (3, 4), (12, 3)] Explanation : All None tuples are removed.Input : test_list = [(None, None), (None, None), (3, 4), (12, 3), (None, )] Output : [(
6 min read
Python | Remove given element from the list
Given a list, write a Python program to remove the given element (list may have duplicates) from the given list. There are multiple ways we can do this task in Python. Let's see some of the Pythonic ways to do this task. Example: Input: [1, 8, 4, 9, 2] Output: [1, 8, 4, 2] Explanation: The Element 9
7 min read
Python | Remove duplicate tuples from list of tuples
Given a list of tuples, Write a Python program to remove all the duplicated tuples from the given list. Examples: Input : [(1, 2), (5, 7), (3, 6), (1, 2)] Output : [(1, 2), (5, 7), (3, 6)] Input : [('a', 'z'), ('a', 'x'), ('z', 'x'), ('a', 'x'), ('z', 'x')] Output : [('a', 'z'), ('a', 'x'), ('z', 'x
5 min read
Python - Assign pair elements from Tuple Lists
Given a tuple list, assign each element, its pair elements from other similar pairs. Input : test_list = [(5, 3), (7, 5), (8, 4)] Output : {5: [3], 7: [5], 8: [4], 4: []} Explanation : 1st elements are paired with respective 2nd elements from all tuples. Input : test_list = [(5, 3)] Output : {5: [3]
7 min read
Python - Remove space between tuple elements
Sometimes, while working with Tuples, we can have a problem in which we need to print tuples, with no space between the comma and next element, which by convention, is present. This problem can have use in day-day and school programming. Let's discuss certain ways in which this task can be performed
6 min read