![]() |
VOOZH | about |
Given Tuple list, filter tuples which are having just int data type.
Input : [(4, 5, "GFg"), (3, ), ("Gfg", )]
Output : [(3, )]
Explanation : 1 tuple (3, ) with all integral values.Input : [(4, 5, "GFg"), (3, "Best" ), ("Gfg", )]
Output : []
Explanation : No tuple with all integers.
Method #1 : Using loop + isinstance()
In this, we iterate the each tuple and check for data type other than int, using isinstance(), if found tuple is flagged off and omitted.
The original list is : [(4, 5, 'GFg'), (5, 6), (3, ), ('Gfg', )]
Filtered tuples : [(5, 6), (3, )]Time Complexity: O(n^2), where n is the number of tuples in the list.
Auxiliary Space: O(n), as the filtered list is stored in res_list and its size is proportional to the number of tuples in the list.
Method #2 : Using all() + list comprehension + isinstance()
In this, all() is used to check if all elements are integers using isinstance(), if that checks, tuples are added to result.
The original list is : [(4, 5, 'GFg'), (5, 6), (3, ), ('Gfg', )]
Filtered tuples : [(5, 6), (3, )]Time Complexity: O(n*n), where n is the length of the input list.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the list “test_list”.
Method 3: Use the filter() function along with lambda function
Step-by-step approach:
The original list is : [(4, 5, 'GFg'), (5, 6), (3,), ('Gfg',)]
Filtered tuples : [(5, 6), (3,)]Time complexity: O(n), where n is the number of tuples in the list.
Auxiliary space: O(k), where k is the number of tuples that satisfy the condition specified in the lambda function.
Method 4: Using reduce()
Step-by-step approach:
The original list is : [(4, 5, 'GFg'), (5, 6), (3,), ('Gfg',)]
Filtered tuples : [(5, 6), (3,)]Time complexity: O(n^2), where n is the length of the input list.
Auxiliary space: O(n), where n is the length of the input list, for the filtered list.