I would use collections.Counter :
from collections import Counter x = [1, 2, 2, 2, 3, 4, 5, 6, 6, 7] counts = Counter(x) output = [value for value, count in counts.items() if count > 1]
Here is another version that preserves the order when the element was first duplicated, which assumes that the sequence just passed contains hashable elements, and it will return to when set or yeild entered into the language (whenever it was).
def keep_dupes(iterable): seen = set() dupes = set() for x in iterable: if x in seen and x not in dupes: yield x dupes.add(x) else: seen.add(x) print list(keep_dupes([1,2,2,2,3,4,5,6,6,7]))
mgilson
source share