Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Find Unique Elements from Tuple in Python
Next article icon

Python – Unique Kth positioned tuples

Last Updated : 08 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
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.



Next Article
Find Unique Elements from Tuple in Python
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python List-of-Tuples
  • Python list-programs
Practice Tags :
  • python

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences