How can I find the duplicates in a Python list and create another list of the duplicates? The list only contains integers.
Python 3.8 one-liner if you don't care to write your own algorithm or use libraries:
l = [1,2,3,2,1,5,6,5,5,5]
res = [(x, count) for x, g in groupby(sorted(l)) if (count := len(list(g))) > 1]
print(res)
Prints item and count:
[(1, 2), (2, 2), (5, 4)]
groupby
takes a grouping function so you can define your groupings in different ways and return additional Tuple
fields as needed.
groupby
is lazy so it shouldn't be too slow.