Skip to content
Related Articles

Related Articles

Python – Remove Equilength and Equisum Tuple Duplicates

Improve Article
Save Article
  • Last Updated : 17 Feb, 2022
Improve Article
Save Article

Sometimes, while working with Python tuples, we can have a problem in which we need to remove duplicates on basis of equal length and equal sum. This kind of problem can also be broken to accommodate any one of the required conditions. This kind of problem can occur in data domains and day-day programming. Let’s discuss certain ways in which this task can be performed.
 

Input : test_list = [(1, 2, 0), (3, 0), (2, 1)] 
Output : [(1, 2, 0), (3, 0)]
Input : test_list = [(1, 2, 0), (3, 0, 0), (0, 2, 1)] 
Output : [(1, 2, 0)] 
 

Method #1: Using nested loops 
This is one of the ways in which this task can be performed. This is the brute force method, in which we loop for each tuple, a matching tuple w.r.t size and sum, and perform the removal.
 

Python3




# Python3 code to demonstrate working of
# Remove Equilength and Equisum Tuple Duplicates
# Using nested loop
 
# initializing lists
test_list = [(4, 5, 6), (3, 0), (2, 1), (1, 2, 3), (5, 5, 5)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Remove Equilength and Equisum Tuple Duplicates
# Using nested loop
res = []
for sub in test_list:
    for sub1 in res:
        if len(sub) == len(sub1) and sum(sub) == sum(sub1):
            break
    else:
        res.append(sub)
 
# printing result
print("Tuples after filtration : " + str(res))

Output

The original list is : [(4, 5, 6), (3, 0), (2, 1), (1, 2, 3), (5, 5, 5)]
Tuples after filtration : [(4, 5, 6), (3, 0), (1, 2, 3)]

 
Method #2 : Using dict() + values() 
The combination of the above functions offers another way to solve this problem. In this, we just harness the property of the dictionary of having unique keys and create a tuple key with len and sum of tuples. The duplicates are thus, avoided.
 

Python3




# Python3 code to demonstrate working of
# Remove Equilength and Equisum Tuple Duplicates
# Using dict() + values()
 
# initializing lists
test_list = [(4, 5, 6), (3, 0), (2, 1), (1, 2, 3), (5, 5, 5)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Remove Equilength and Equisum Tuple Duplicates
# Using dict() + values()
res = list({(len(sub), sum(sub)): sub for sub in test_list}.values())
 
# printing result
print("Tuples after filtration : " + str(res))

Output

The original list is : [(4, 5, 6), (3, 0), (2, 1), (1, 2, 3), (5, 5, 5)]
Tuples after filtration : [(5, 5, 5), (2, 1), (1, 2, 3)]

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!