Python - Filter unique valued tuples
Last Updated :
25 Apr, 2023
Given a Tuple list, filter tuples that don't contain duplicates.
Input : test_list = [(3, 5, 6, 7), (3, 2, 4, 3), (9, 4, 9), (2, 3, 2)]
Output : [(3, 5, 6, 7)]
Explanation : Rest all tuples have duplicate values.
Input : test_list = [(3, 5, 6, 7, 7), (3, 2, 4, 3), (9, 4, 9), (2, 3, 2)]
Output : []
Explanation : All tuples have duplicate values.
Method #1 : Using loop + set()
In this, all the tuples are iterated, and duplicacy test is done using set(), if the length of the set is the same as the tuple, it doesn't contain a duplicate.
Python3
# Python3 code to demonstrate working of
# Filter unique valued tuples
# Using loop + set()
# initializing list
test_list = [(3, 5, 6, 7), (3, 2, 4, 3), (9, 4), (2, 3, 2)]
# printing original list
print("The original list is : " + str(test_list))
res = []
for sub in test_list:
# checking lengths to be equal
if len(set(sub)) == len(sub):
res.append(sub)
# printing results
print("Filtered tuples : " + str(res))
OutputThe original list is : [(3, 5, 6, 7), (3, 2, 4, 3), (9, 4), (2, 3, 2)]
Filtered tuples : [(3, 5, 6, 7), (9, 4)]
Method #2: Using list comprehension
This performs a similar task as above, the difference being that this is one-liner and compact.
Python3
# Python3 code to demonstrate working of
# Filter unique valued tuples
# Using list comprehension
# initializing list
test_list = [(3, 5, 6, 7), (3, 2, 4, 3), (9, 4), (2, 3, 2)]
# printing original list
print("The original list is : " + str(test_list))
# list comprehension used to filter
res = [sub for sub in test_list if len(set(sub)) == len(sub)]
# printing results
print("Filtered tuples : " + str(res))
OutputThe original list is : [(3, 5, 6, 7), (3, 2, 4, 3), (9, 4), (2, 3, 2)]
Filtered tuples : [(3, 5, 6, 7), (9, 4)]
Method #3: Without using any builtin methods
Python3
# Python3 code to demonstrate working of
# Filter unique valued tuples
# initializing list
test_list = [(3, 5, 6, 7), (3, 2, 4, 3), (9, 4), (2, 3, 2)]
# printing original list
print("The original list is : " + str(test_list))
res = []
def checkUnique(lis):
x = []
for i in lis:
if i not in x:
x.append(i)
x = tuple(x)
if(x == lis):
return True
return False
for sub in test_list:
if(checkUnique(sub)):
res.append(sub)
# printing results
print("Filtered tuples : " + str(res))
OutputThe original list is : [(3, 5, 6, 7), (3, 2, 4, 3), (9, 4), (2, 3, 2)]
Filtered tuples : [(3, 5, 6, 7), (9, 4)]
Method #4:Using filter()+set()+map()
Algorithm:
- Initialize an empty list res to store the filtered tuples.
- Iterate through each tuple sub in test_list.
- Check if the length of the set of elements in sub is equal to the length of sub.
- If the lengths are equal, it means all the elements in sub are unique, so append sub to res.
- Finally, print the res list containing the filtered tuples.
Python3
# Python3 code to demonstrate working of
# Filter unique valued tuples
# Using filter() + lambda + set()
# initializing list
test_list = [(3, 5, 6, 7), (3, 2, 4, 3), (9, 4), (2, 3, 2)]
# printing original list
print("The original list is : " + str(test_list))
# using filter() and lambda to filter tuples with unique values
res = list(filter(lambda tpl: len(tpl) == len(set(tpl)), test_list))
# printing results
print("Filtered tuples : " + str(res))
OutputThe original list is : [(3, 5, 6, 7), (3, 2, 4, 3), (9, 4), (2, 3, 2)]
Filtered tuples : [(3, 5, 6, 7), (9, 4)]
Time complexity: O(n*m), where n is the number of tuples in the list test_list and m is the maximum length of a tuple in test_list. The time complexity of set() is O(n), so the loop over the tuples dominates the overall time complexity.
Auxiliary Space: O(n), where n is the number of tuples in the list test_list. This is because the size of the output list res is proportional to the number of tuples in the input list.
Method#5: Using the Recursive method
Algorithm:
- Define the filter_unique_tuples function that takes in a list test_list as input.
- If the length of test_list is 0, return an empty list.
- Otherwise, extract the first tuple first from test_list and recursively apply filter_unique_tuples to the rest of the list (test_list[1:]), storing the result in rest.
- If the length of the set of values in first is equal to the length of first (meaning all values are unique), append first to rest and return the resulting list ([first] + rest).
- Otherwise, return only the rest.
Python3
# Python3 code to demonstrate working of
# Filter unique valued tuples
def filter_unique_tuples(test_list):
if len(test_list) == 0:
return []
else:
first = test_list[0]
rest = filter_unique_tuples(test_list[1:])
if len(set(first)) == len(first):
return [first] + rest
else:
return rest
# initializing list
test_list = [(3, 5, 6, 7), (3, 2, 4, 3), (9, 4), (2, 3, 2)]
# printing original list
print("The original list is : " + str(test_list))
res = filter_unique_tuples(test_list)
# printing results
print("Filtered tuples : " + str(res))
OutputThe original list is : [(3, 5, 6, 7), (3, 2, 4, 3), (9, 4), (2, 3, 2)]
Filtered tuples : [(3, 5, 6, 7), (9, 4)]
Time Complexity: O(n^2)
Let n be the length of the input list test_list. In the worst case, all tuples in the list have unique values, so the function needs to examine all n tuples. Each tuple has a length that is at most n, so computing the set of values for each tuple takes time O(n). Therefore, the time complexity of the function is O(n^2).
Auxiliary Space: O(n)
The space complexity of the function is O(n), which is the maximum depth of the recursion stack. This is because each recursive call adds a new frame to the stack, which contains only the variables first and rest.
Method #6: Using dictionary comprehension
we can create a dictionary comprehension where the keys are the tuples themselves and the values are the number of unique elements in the tuple. Then, you can filter the dictionary to only include tuples with the same number of unique elements as the length of the tuple itself.
Python3
test_list = [(3, 5, 6, 7), (3, 2, 4, 3), (9, 4), (2, 3, 2)]
# create a dictionary of tuples with
their number of unique elements
unique_counts = {t: len(set(t)) for t in test_list}
# filter the dictionary to only include tuples
# with the same number of unique elements
# as the length of the tuple itself
res = [t for t, count in unique_counts.items() if count == len(t)]
print("Filtered tuples : " + str(res))
OutputFiltered tuples : [(3, 5, 6, 7), (9, 4)]
Time complexity: O(n), where n is the number of tuples in the input list.
Auxiliary space: O(n), since we are creating a dictionary with n key-value pairs.
Similar Reads
Python | Unique values in Matrix
Sometimes we need to find the unique values in a list, which is comparatively easy and has been discussed earlier. But we can also get a matrix as input i.e a list of lists, and finding unique in them are discussed in this article. Let's see certain ways in which this can be achieved. Method #1: Usi
9 min read
Python | Get unique tuples from list
Sometimes, while working with Python list, we can come across a problem in which we require to find the unique occurrences of list. Having elementary data types is easy to handle, but sometime, we might have complex data types and the problem becomes new in that cases. Let's discuss certain ways in
3 min read
Python - Unique Kth positioned tuples
Sometimes, while working with Python records, we can have a problem in which we need to extract only the unique tuples, based on some particular index of tuples. This kind of problem can have applications in domains such as web development. Let's discuss certain ways in which this task can be perfor
8 min read
Python | Assign value to unique number in list
We can assign all the numbers in a list a unique value that upon repetition it retains that value retained to it. This is a very common problem that is faced in web development when playing with id's. Let's discuss certain ways in which this problem can be solved. Method #1: Using enumerate() + list
7 min read
Python - Union of Tuples
Sometimes, while working with tuples, we can have a problem in which we need union of two records. This type of application can come in Data Science domain. Letâs discuss certain ways in which this problem can be solved. Method #1 : Using set() + "+" operator This task can be performed using union f
2 min read
Python program to unique keys count for Value in Tuple List
Given dual tuples, get a count of unique keys for each value present in the tuple. Input : test_list = [(3, 4), (1, 2), (2, 4), (8, 2), (7, 2), (8, 1), (9, 1), (8, 4), (10, 4)] Output : {4: 4, 2: 3, 1: 2} Explanation : 3, 2, 8 and 10 are keys for value 4. Input : test_list = [(3, 4), (1, 2), (8, 1),
6 min read
Unzip List of Tuples in Python
The task of unzipping a list of tuples in Python involves separating the elements of each tuple into individual lists, based on their positions. For example, given a list of tuples like [('a', 1), ('b', 4)], the goal is to generate two separate lists: ['a', 'b'] for the first elements and [1, 4] for
2 min read
Python - Filter Tuples with Integers
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 : Usi
5 min read
Python - Extract Unique value key pairs
Sometimes, while working on Python dictionaries, we can have a problem in which we need to perform the extraction of selected pairs of keys from dictionary list, that too unique. This kind of problem can have application in many domains including day-day programming. Let's discuss certain ways in wh
5 min read
Python - Minimum in tuple list value
Many times, while dealing with containers in any language we come across lists of tuples in different forms, tuples in themselves can have sometimes more than native datatypes and can have list as their attributes. This article talks about the minimum of list as tuple attribute. Letâs discuss certai
5 min read