Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python - Total equal pairs in List
When it is required to find the total equal pairs in a list, we can use the set() function along with the floor division operator // and iteration. This approach counts how many pairs can be formed from duplicate elements in the list.
Example
Below is a demonstration of finding equal pairs in a list −
numbers = [34, 56, 12, 32, 78, 99, 67, 34, 52, 78, 99, 10, 0, 11, 23, 9]
print("The list is :")
print(numbers)
unique_elements = set(numbers)
total_pairs = 0
for element in unique_elements:
total_pairs += numbers.count(element) // 2
print("The total pairs are :")
print(total_pairs)
Output
The list is : [34, 56, 12, 32, 78, 99, 67, 34, 52, 78, 99, 10, 0, 11, 23, 9] The total pairs are : 3
How It Works
The algorithm works by following these steps −
Convert the list to a set to get unique elements, eliminating duplicates for iteration
For each unique element, count its occurrences in the original list using
count()Use floor division
//by 2 to find how many pairs can be formed from that elementSum up all the pairs from different elements to get the total
Alternative Method Using Counter
You can also use Python's Counter from the collections module for a more efficient approach −
from collections import Counter
numbers = [34, 56, 12, 32, 78, 99, 67, 34, 52, 78, 99, 10, 0, 11, 23, 9]
print("The list is :")
print(numbers)
element_counts = Counter(numbers)
total_pairs = sum(count // 2 for count in element_counts.values())
print("The total pairs are :")
print(total_pairs)
The list is : [34, 56, 12, 32, 78, 99, 67, 34, 52, 78, 99, 10, 0, 11, 23, 9] The total pairs are : 3
Conclusion
Use the set-based approach for simple cases or Counter for better performance with large lists. Both methods use floor division to count pairs effectively from duplicate elements.
