Keep duplicates in a list in Python

I know this is probably the easy answer, but I can't figure it out. What is the best thing in Python to keep duplicates in a list:

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

The output should be:

 [2,6] 

I found this link: Find (and save) duplicate subscriptions in python , but I'm still relatively new to Python and I can't get it to work for a simple list.

+7
source share
3 answers

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

 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] 
+8
source

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])) 
+12
source

save is simple:

 array2 = [] aux = 0 aux2=0 for i in x: aux2 = i if(aux2==aux): array2.append(i) aux= i list(set(array2)) 

This should work

0
source

All Articles