How can I find the duplicates in a Python list and create another list of the duplicates? The list only contains integers.
We can use itertools.groupby in order to find all the items that have dups:
from itertools import groupby
myList = [2, 4, 6, 8, 4, 6, 12]
# when the list is sorted, groupby groups by consecutive elements which are similar
for x, y in groupby(sorted(myList)):
# list(y) returns all the occurences of item x
if len(list(y)) > 1:
print x
The output will be:
4
6