Open In App

Python – Unique Kth positioned tuples

Last Updated : 08 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




# Python3 code to demonstrate working of
# Unique Kth index tuples
# Using map() + next() + lambda
 
# initializing list
test_list = [(5, 6, 8), (4, 2, 7), (1, 2, 3), (9, 6, 5)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 2
 
# Unique Kth index tuples
# Using map() + next() + lambda
res = [*map(lambda ele: next(tup for tup in test_list if tup[K - 1] == ele),
            {tup[K - 1] for tup in test_list})]
 
# printing result
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




# Python3 code to demonstrate working of
# Unique Kth index tuples
# Using next() + groupby() + lambda
from itertools import groupby
 
# initializing list
test_list = [(5, 6, 8), (4, 2, 7), (1, 2, 3), (9, 6, 5)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 2
 
# Unique Kth index tuples
# Using next() + groupby() + lambda
 
 
def temp(ele): return ele[K - 1]
 
 
res = [next(val) for _, val in groupby(sorted(test_list, key=temp), key=temp)]
 
# printing result
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




# Python3 code to demonstrate working of
# Unique Kth index tuples
 
# initializing list
test_list = [(5, 6, 8), (4, 2, 7), (1, 2, 3), (9, 6, 5)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
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
# printing result
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

  1. Create an empty set unique_set.
  2. Create an empty list res.
  3. Iterate through each tuple tup in the test_list.
  4. Check if the Kth element of tup is in unique_set.
  5. If it is not in unique_set, add it to unique_set and append tup to res.
  6. If it is already in unique_set, do nothing.
  7. Print the list res.

Python3




# Python3 code to demonstrate working of
# Unique Kth index tuples
# Using a set and a list comprehension
 
# initializing list
test_list = [(5, 6, 8), (4, 2, 7), (1, 2, 3), (9, 6, 5)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 2
 
# Unique Kth index tuples
# Using a set and a list comprehension
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])]
 
# printing result
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




# Python3 code to demonstrate working of
# Unique Kth index tuples
# Using a dictionary and a loop
 
# initializing list
test_list = [(5, 6, 8), (4, 2, 7), (1, 2, 3), (9, 6, 5)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 2
 
# Unique Kth index tuples
# Using a dictionary and a loop
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)
 
# printing result
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:

  1. Initialize the input list test_list and K.
  2. Define an empty dictionary unique_dict and an empty list res to store unique tuples.
  3. Loop through each tuple in the test_list.
  4. Check whether the Kth index element of the current tuple is already in the unique_dict.
  5. If not, add the Kth index element to the unique_dict and append the current tuple to the res list.
  6. Return the res list as the result.
  7. Print the result.

Python3




from functools import reduce
 
test_list = [(5, 6, 8), (4, 2, 7), (1, 2, 3), (9, 6, 5)]
K = 2
# printing original list
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))
#This code is contrinuted by Pushpa.


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




# Python3 code to demonstrate working of
# Unique Kth index tuples
# Using filter() and lambda function
 
# initializing list
test_list = [(5, 6, 8), (4, 2, 7), (1, 2, 3), (9, 6, 5)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 2
 
# Unique Kth index tuples
# Using filter() and lambda function
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))
 
# printing result
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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads