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 Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read