Find count of number of pairs in the list

Viewed 1087

I have list of numbers:

[5, 4, 3, 4, 2, 1, 3, 5, 3, 5, 3, 5,]

A pair of numbers is the same 2 numbers. For example, 5 occurs 4 times, so we have 2 pairs of 5s. In the list above I can say I have 5 pairs. I want the output to count how many pairs of numbers are in the list.

I tried this, but got stuck.

list = [5,4,3,4,2,1,3,5]
print(list)
temp = 0
new_list = []
for index,x in enumerate(list):
    elm_count = list.count(list[index])
    if new_list:
        for ind, y in enumerate(new_list):
            if list[index] == new_list[ind]:
                continue
                if not elm_count % 2:
                    occ_count = elm_count/2
                    temp += occ_count
                    new_list.append(list[index])
                    continue
2 Answers

Simpler way to achieve this is using collections.Counter() with sum() as:

>>> my_list = [5, 4, 3, 4, 2, 1, 3, 5,3, 5, 3, 5,]

>>> sum(num//2 for num in Counter(my_list).values())
5

Here Counter() will generate a dict with number as key and count of occurrence of number in list as its value. Then I am iterating over its values and calculating the count of pairs for each number using generator expression, and doing summation on the count of all the pairs using sum().

You can refer below documents for more details:

To add, a solution without importing a package:

#  Accepts a list of numbers as argument
def get_pairs(l):
    already_counted = []
    list_of_pairs = []
    for i in l:
        if not i in already_counted:
            already_counted.append(i)
            list_of_pairs.append(ar.count(i)//2)
    
    return sum(list_of_pairs)

get_pairs([4,3,3,4,2,3,2,1,5]) # Run
Related