Stand at each value and look back
At a reunion, everyone shakes hands with each old classmate from their year. How many handshakes? One way to count: as each person arrives, they shake hands with everyone from their year who's already there.
Counting equal pairs works the same way. Walk the list, and at each value ask: how many copies of this value came before me? Each of them makes a pair with this one. A map of counts so far answers that in one lookup.
No 2s before. pairs = 0, then seen = {2: 1}.
Ask first, then add yourself
Order matters. First add the number of earlier copies to the answer. Then add 1 to this value's count, so that later copies can pair with this one.
Do it the other way round and every value pairs with itself. And use a 64-bit number for the answer: a million equal values make about 500 billion pairs.
seen = {}
pairs = 0
for x in nums:
pairs += seen.get(x, 0)
seen[x] = seen.get(x, 0) + 1
return pairs