Record Similar tuple occurrences in Python

When it is required to record similar tuple occurrences, the map() method, the Counter method and the sorted() method can be used.

A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on). A list of tuple basically contains tuples enclosed in a list.

The map() function applies a given function/operation to every item in an iterable (such as list, tuple). It returns a map object as the result.

The sorted() method is used to sort the elements of a list.

The Counter is a sub-class from the collections module that helps count hashable objects. It creates a hash table on its own when invoked on an iterable like a list or tuple.

Example

from collections import Counter

my_list_1 = [(11, 14), (0, 78), (33, 67), (89, 0), (14, 11), (78, 0)]

print("The list of tuple is:")
print(my_list_1)

my_result = dict(Counter(tuple(elem) for elem in map(sorted, my_list_1)))
print("The frequency of like tuples is:")
print(my_result)
The list of tuple is:
[(11, 14), (0, 78), (33, 67), (89, 0), (14, 11), (78, 0)]
The frequency of like tuples is:
{(11, 14): 2, (0, 78): 2, (33, 67): 1, (0, 89): 1}

How It Works

The algorithm works by normalizing tuples before counting them ?

  1. Sorting: Each tuple is sorted using map(sorted, my_list_1)
  2. Tuple conversion: Sorted lists are converted back to tuples
  3. Counting: Counter counts occurrences of identical sorted tuples
  4. Dictionary conversion: Result is converted to a regular dictionary

Step-by-Step Breakdown

from collections import Counter

# Original tuples with some that are similar when sorted
tuples_list = [(11, 14), (0, 78), (14, 11), (78, 0)]

print("Original tuples:", tuples_list)

# Step 1: Sort each tuple
sorted_tuples = list(map(sorted, tuples_list))
print("After sorting each tuple:", sorted_tuples)

# Step 2: Convert back to tuples
normalized_tuples = [tuple(elem) for elem in sorted_tuples]
print("Normalized tuples:", normalized_tuples)

# Step 3: Count occurrences
result = Counter(normalized_tuples)
print("Count result:", result)
Original tuples: [(11, 14), (0, 78), (14, 11), (78, 0)]
After sorting each tuple: [[11, 14], [0, 78], [11, 14], [0, 78]]
Normalized tuples: [(11, 14), (0, 78), (11, 14), (0, 78)]
Count result: Counter({(11, 14): 2, (0, 78): 2})

Conclusion

This approach effectively identifies similar tuples by normalizing their order through sorting, then counting occurrences. It's useful for finding patterns in data where the order of tuple elements doesn't matter.

Updated on: 2026-03-25T17:28:04+05:30

156 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements