Python – Unique Kth positioned tuples
Last Updated : 08 May, 2023
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 performed.
Input : test_list = [(5, 6, 5), (4, 2, 7), (1, 2, 3), (9, 6, 5)] K = 3
Output : [(1, 2, 3), (5, 6, 5), (4, 2, 7)]
Input : test_list = [(5, ), (1, ), (1, ), (9, )] K = 1
Output : [(1, ), (5, ), (9, )]
Method #1 : Using map() + next() + lambda The combination of above functions can be used to solve this problem. In this, we extend the logic of getting unique elements extracted using lambda function and next(), using map().
Python3
test_list = [( 5 , 6 , 8 ), ( 4 , 2 , 7 ), ( 1 , 2 , 3 ), ( 9 , 6 , 5 )] print ( "The original list is : " + str (test_list)) K = 2 res = [ * map ( lambda ele: next (tup for tup in test_list if tup[K - 1 ] = = ele), {tup[K - 1 ] for tup in test_list})] print ( "The extracted elements : " + str (res)) |
Output : The original list is : [(5, 6, 8), (4, 2, 7), (1, 2, 3), (9, 6, 5)] The extracted elements : [(4, 2, 7), (5, 6, 8)]
Time Complexity: O(n*n) where n is the number of elements in the in the list “test_list”. The map() + next() + lambda is used to perform the task and it takes O(n*n) time.
Auxiliary Space: O(n), the algorithm uses an additional list to store the result, thus consuming linear space which is O(n).
Method #2 : Using next() + groupby() + lambda The combination of above functions can also be used to solve this problem. In this, we perform task of map() in above using groupby(), in a more compact way.
Python3
from itertools import groupby test_list = [( 5 , 6 , 8 ), ( 4 , 2 , 7 ), ( 1 , 2 , 3 ), ( 9 , 6 , 5 )] print ( "The original list is : " + str (test_list)) K = 2 def temp(ele): return ele[K - 1 ] res = [ next (val) for _, val in groupby( sorted (test_list, key = temp), key = temp)] print ( "The extracted elements : " + str (res)) |
Output : The original list is : [(5, 6, 8), (4, 2, 7), (1, 2, 3), (9, 6, 5)] The extracted elements : [(4, 2, 7), (5, 6, 8)]
Time Complexity: O(n*logn), where n is the length of the input list test_list.
Auxiliary Space: O(n)
Method #3 : Using loops ,in and not in operators
Python3
test_list = [( 5 , 6 , 8 ), ( 4 , 2 , 7 ), ( 1 , 2 , 3 ), ( 9 , 6 , 5 )] print ( "The original list is : " + str (test_list)) K = 2 a = [] for i in test_list: if i[K - 1 ] not in a: a.append(i[K - 1 ]) res = [] for i in a: for j in test_list: if (j[K - 1 ] = = i): res.append(j) break print ( "The extracted elements : " + str (res)) |
Output The original list is : [(5, 6, 8), (4, 2, 7), (1, 2, 3), (9, 6, 5)] The extracted elements : [(5, 6, 8), (4, 2, 7)]
Time complexity: O(n^2) in the worst case, where n is the length of the input list
Auxiliary space: O(n) for the list a and the result list res, where n is the length of the input list.
Method 4: Using a set and a list comprehension
- Create an empty set unique_set.
- Create an empty list res.
- Iterate through each tuple tup in the test_list.
- Check if the Kth element of tup is in unique_set.
- If it is not in unique_set, add it to unique_set and append tup to res.
- If it is already in unique_set, do nothing.
- Print the list res.
Python3
test_list = [( 5 , 6 , 8 ), ( 4 , 2 , 7 ), ( 1 , 2 , 3 ), ( 9 , 6 , 5 )] print ( "The original list is : " + str (test_list)) K = 2 unique_set = set () res = [tup for tup in test_list if tup[K - 1 ] not in unique_set and not unique_set.add(tup[K - 1 ])] print ( "The extracted elements : " + str (res)) |
Output The original list is : [(5, 6, 8), (4, 2, 7), (1, 2, 3), (9, 6, 5)] The extracted elements : [(5, 6, 8), (4, 2, 7)]
Time complexity: O(n), where n is the length of test_list.
Auxiliary space: O(n), where n is the length of test_list.
Method #5: Using a dictionary and a loop
Step-by-step approach:
- Create an empty dictionary unique_dict to store unique elements.
- Loop through the list of tuples test_list.
- Check if the K-th index element of the tuple is already in the unique_dict.
- If it is not in the dictionary, add it to the dictionary and append the tuple to the result list res.
- If it is already in the dictionary, do not append the tuple to the result list.
- Return the result list res.
Below is the implementation of the above approach:
Python3
test_list = [( 5 , 6 , 8 ), ( 4 , 2 , 7 ), ( 1 , 2 , 3 ), ( 9 , 6 , 5 )] print ( "The original list is : " + str (test_list)) K = 2 unique_dict = {} res = [] for tup in test_list: if tup[K - 1 ] not in unique_dict: unique_dict[tup[K - 1 ]] = True res.append(tup) print ( "The extracted elements : " + str (res)) |
Output The original list is : [(5, 6, 8), (4, 2, 7), (1, 2, 3), (9, 6, 5)] The extracted elements : [(5, 6, 8), (4, 2, 7)]
Time complexity: O(n), where n is the length of the test_list.
Auxiliary space: O(n), to store the dictionary unique_dict.
Method #6: Using reduce():
Algorithm:
- Initialize the input list test_list and K.
- Define an empty dictionary unique_dict and an empty list res to store unique tuples.
- Loop through each tuple in the test_list.
- Check whether the Kth index element of the current tuple is already in the unique_dict.
- If not, add the Kth index element to the unique_dict and append the current tuple to the res list.
- Return the res list as the result.
- Print the result.
Python3
from functools import reduce test_list = [( 5 , 6 , 8 ), ( 4 , 2 , 7 ), ( 1 , 2 , 3 ), ( 9 , 6 , 5 )] K = 2 print ( "The original list is : " + str (test_list)) res = reduce ( lambda acc, tup: acc + [tup] if tup[K - 1 ] not in [t[K - 1 ] for t in acc] else acc, test_list, []) print ( "The extracted elements : " + str (res)) |
Output The original list is : [(5, 6, 8), (4, 2, 7), (1, 2, 3), (9, 6, 5)] The extracted elements : [(5, 6, 8), (4, 2, 7)]
Time Complexity: O(n), where n is the length of the input list.
The time complexity of the for loop is O(n) and the time complexity of the dictionary lookups and list append operations inside the loop is O(1).
Space Complexity: O(n), where n is the length of the input list.
The space complexity is dominated by the dictionary unique_dict and the list res, which can each potentially store up to n elements.
Method #7 : Using filter() and lambda function
- We can use the filter() function along with a lambda function to filter out tuples whose Kth index value is not unique
- In the lambda function, we create a set of all the Kth index values seen so far and check if the current tuple’s Kth index value is already in the set or not
- If it is not in the set, we add it to the set and return True to keep the tuple in the filtered list
- If it is already in the set, we return False to filter it out
- Finally, we convert the filtered result to a list using the list() function.
Python3
test_list = [( 5 , 6 , 8 ), ( 4 , 2 , 7 ), ( 1 , 2 , 3 ), ( 9 , 6 , 5 )] print ( "The original list is : " + str (test_list)) K = 2 unique_set = set () res = list ( filter ( lambda tup: tup[K - 1 ] not in unique_set and not unique_set.add(tup[K - 1 ]), test_list)) print ( "The extracted elements : " + str (res)) |
Output The original list is : [(5, 6, 8), (4, 2, 7), (1, 2, 3), (9, 6, 5)] The extracted elements : [(5, 6, 8), (4, 2, 7)]
Time complexity: O(n)
Auxiliary space: O(n) for the set to keep track of unique Kth index values.
Similar Reads
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 - Filter unique valued tuples
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 : [] E
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 - 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
Find Unique Elements from Tuple in Python
Tuples are immutable built-in data type in Python that can store multiple values in it. Extracting Unique Elements from a Tuple in Python can be done through two different approaches. Examples: Input: (1, 2, 13, 4, 3, 12, 5, 7, 7, 2, 2, 4)Output: (1, 2, 3,4,5,12,13)Input: ('Apple', 'Mango', 'Banana'
5 min read
Python | Tuple multiplication
Sometimes, while working with records, we can have a problem in which we may need to perform multiplication of tuples. This problem can occur in day-day programming. Let's discuss certain ways in which this task can be performed. Method #1 : Using zip() + generator expression The combination of abov
5 min read
Python | How to get unique elements in nested tuple
Sometimes, while working with tuples, we can have a problem in which we have nested tuples and we need to extract elements that occur singly, i.e are elementary. This kind of problem can have applications in many domains. Let's discuss certain ways in which this problem can be solved. Method #1: Usi
7 min read
Python - Unique Tuple Frequency (Order Irrespective)
Given tuple list, extract the frequency of unique tuples in list order irrespective. Input : test_list = [(3, 4), (1, 2), (4, 3), (3, 4)] Output : 2 Explanation : (3, 4), (4, 3), (3, 4) makes 1 and (1, 2) is 2nd unique element. Input : test_list = [(3, 7), (1, 2), (4, 3), (5, 6)] Output : 4 Explanat
5 min read
Python | Extract unique tuples from list, Order Irrespective
Sometimes, while working with data, we can have a problem in which we need to check for similar records and eradicate them. When elements are ordered, this case has been discussed before. But sometimes, we might have to ignore the order and has to be removed in case similar elements occur. Let's dis
5 min read
Addition in Nested Tuples - Python
Sometimes, while working with records, we can have a problem in which we require to perform index wise addition of tuple elements. This can get complicated with tuple elements to be tuple and inner elements again be tuple. Let's discuss certain ways in which this problem can be solved. Method #1: Us
6 min read