0

In a list, they are many items, and some of them can occur more than once. How can I get the number of those items which occur multiple times in a list, in Python? For example, in below list, a and b occur multiple times. So in this case, I get two.

list = [ 'a', 'b', 'a', 'b', 'c', 'd', 'e', 'a', 'b', 'h', 'u', 'i', 'x', 'b', 'e', 'h', 'j', 'w' ]
martineau
  • 119,623
  • 25
  • 170
  • 301

2 Answers2

3

Since the Counter solution is already taken, here's something different:

>>> lst.sort()
>>> len(set(lst[::2]) & set(lst[1::2]))
4

This first sorts, so then equal values are next to each other. Meaning a duplicated value appears both in the even-index places and in the odd-index places, so intersection them gets me all duplicated values (and of course none of the unique values, as those are either at an even index or at an odd index, not at both).

This has complexity O(n log n) due to sorting, of course, so at least for large lists I'd expect it to be slower than the Counter solution with its O(n) complexity.

superb rain
  • 5,300
  • 2
  • 11
  • 25
1

Using this answer to the question How do I find the duplicates in a list and create another list with them?, can do:

import collections
print(len([item for item, count in collections.Counter(l).items() if count > 1]))

You get 4 because that is how many items are repeated in the list (ie a, b, e, h all appear more than once).

Can use other solutions from the thread of the linked question.

zabop
  • 6,750
  • 3
  • 39
  • 84