py4u blog

Python - Remove Kth Index Duplicates in Tuple

Tuples are an important data structure in Python. They are immutable sequences, which means once created, their elements cannot be changed. However, there might be scenarios where you want to remove duplicates at a specific (Kth) index within a tuple of tuples. In this blog, we'll explore how to achieve this in Python, along with best practices and example usage.

2026-06

Table of Content#

  1. Problem Statement
  2. Approach 1: Using a Loop and a Temporary Data Structure
  3. Approach 2: Using List Comprehension and Set Operations (for Simple Cases)
  4. Best Practices
  5. Example Usage
  6. References

1. Problem Statement#

Suppose you have a tuple of tuples, like my_tuple = ((1, 'a'), (2, 'b'), (1, 'c')). And you want to remove the duplicates at a specific index (say the 0th index in this case). So, the result should be ((1, 'a'), (2, 'b')) as the first element of the first and third inner tuples is the same (1).

2. Approach 1: Using a Loop and a Temporary Data Structure#

Common Practice#

One common way is to iterate over the tuple of tuples and use a temporary data structure (like a list) to keep track of the values we've already seen at the Kth index.

Code Example#

def remove_kth_index_duplicates(tup, k):
    seen = set()
    result = []
    for sub_tup in tup:
        if sub_tup[k] not in seen:
            seen.add(sub_tup[k])
            result.append(sub_tup)
    return tuple(result)
 
# Example usage
my_tuple = ((1, 'a'), (2, 'b'), (1, 'c'))
k = 0
new_tuple = remove_kth_index_duplicates(my_tuple, k)
print(new_tuple)

Explanation#

  • We first initialize an empty set seen to store the values we've encountered at the Kth index.
  • Then we loop through each inner tuple (sub_tup) in the main tuple (tup).
  • For each sub_tup, we check if its value at the Kth index (sub_tup[k]) is not in the seen set. If not, we add that value to the seen set and append the sub_tup to the result list.
  • Finally, we convert the result list back to a tuple and return it.

3. Approach 2: Using List Comprehension and Set Operations (for Simple Cases)#

Common Practice#

When the data is relatively simple and the operations are straightforward, list comprehensions can make the code more concise.

Code Example#

def remove_kth_index_duplicates_list_comp(tup, k):
    seen = set()
    return tuple([sub_tup for sub_tup in tup if not (sub_tup[k] in seen or seen.add(sub_tup[k]))])
 
# Example usage
my_tuple = ((1, 'a'), (2, 'b'), (1, 'c'))
k = 0
new_tuple = remove_kth_index_duplicates_list_comp(my_tuple, k)
print(new_tuple)

Explanation#

  • Here, we again use a set seen.
  • In the list comprehension, for each sub_tup in tup, we check if the value at the Kth index is not already in seen (using the or operator trick where seen.add(sub_tup[k]) returns None and sub_tup[k] in seen is checked first). If the condition is met (i.e., the value is new), the sub_tup is included in the list comprehension result.
  • Finally, we convert the resulting list to a tuple.

4. Best Practices#

  • Immutable Data Consideration: Since tuples are immutable, when creating the result, we first build it as a list (which is mutable) and then convert it back to a tuple. This is a common pattern when working with immutable data structures in Python.
  • Error Handling: In a more production-ready code, you should add error handling. For example, check if k is within the valid range of indices for the inner tuples. You can use try-except blocks or simple if statements to raise appropriate errors (like IndexError) if k is out of bounds.
  • Readability: While the list comprehension approach (Approach 2) can be concise, for more complex logic or when working with a team, the loop-based approach (Approach 1) is often more readable. So, choose the approach based on the complexity of your codebase and the audience who will maintain it.

5. Example Usage#

Let's take another example. Suppose we have a tuple of tuples representing student records where the 1st index is the student ID:

student_records = (('John', 101, 'Math'), ('Alice', 102, 'Science'), ('John', 103, 'History'))
k = 1
new_records = remove_kth_index_duplicates(student_records, k)
print(new_records)

This will remove the duplicate student records based on the student ID (the value at the 1st index).

6. References#

By following these approaches and best practices, you can effectively remove duplicates at a specific index within a tuple of tuples in Python. Whether you choose the loop-based or list comprehension-based method depends on your specific coding context and requirements.