Keep duplicates in a list in Python

This is a short way to do it if the list is sorted already:

x = [1,2,2,2,3,4,5,6,6,7]

from itertools import groupby
print [key for key,group in groupby(x) if len(list(group)) > 1]

I'd use a 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's another version which keeps the order of when the item was first duplicated that only assumes that the sequence passed in contains hashable items and it will work back to when set or yeild was introduced to the language (whenever that 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]))