Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,560 questions

51,419 answers

573 users

How to count the unique tuples in a list of tuples when the order inside each tuple doesn’t matte with Python

2 Answers

0 votes
tpl_lst = [
    (1, 2, 3), (3, 1, 2), (2, 3, 1),
    (4, 5, 6), (8, 7, 1), (6, 4, 5)
]

unique_tuples = set(tuple(sorted(item)) for item in tpl_lst)

print("unique_tuples:", unique_tuples)
print("Total of unique tuples =", len(unique_tuples))



'''
run:

unique_tuples: {(1, 7, 8), (1, 2, 3), (4, 5, 6)}
Total of unique tuples = 3

'''

 



answered 2 days ago by avibootz
0 votes
def unique_unordered_tuples(tpl_lst):
    unique_tuples_list = []
    
    for item in tpl_lst:
        unique_tuple = tuple(sorted(item))  # normalize so order doesn't matter
        if unique_tuple not in unique_tuples_list:
            unique_tuples_list.append(unique_tuple)
    
    return unique_tuples_list, len(unique_tuples_list)



tpl_lst = [
    (1, 2, 3), (3, 1, 2), (2, 3, 1),
    (4, 5, 6), (8, 7, 1), (6, 4, 5)
]

unique_list, total = unique_unordered_tuples(tpl_lst)

print("unique_tuples_list:", unique_list)
print("Total of unique tuples =", total)



'''
run:

unique_tuples_list: [(1, 2, 3), (4, 5, 6), (1, 7, 8)]
Total of unique tuples = 3

'''

 



answered 2 days ago by avibootz
...