Code showing if there are duplicates and their values if there are:
Try it online!
l = [1,4,5,6,7,8,9,9,1,5,7,7]
sl = sorted(l)
has_dups = any(f == s for f, s in zip(sl[:-1], sl[1:]))
dups_vals = sorted(set(f for f, s in zip(sl[:-1], sl[1:]) if f == s))
print('has dups:', has_dups, ', dups values:', dups_vals)
Outputs:
has dups: True , dups values: [1, 5, 7, 9]
Code works lazily, i.e. it sets has_dups
to True
(found duplicate) as soon as the very first duplicate is found in sorted array.
If input array is very large, then numpy
can be used which is magnitude faster than pure Python. Next code implements same task using numpy
(numpy needs to be installed once python -m pip install numpy
):
Try it online!
import numpy as np
l = [1,4,5,6,7,8,9,9,1,5,7,7]
sa = np.sort(l)
has_dups = np.any(sa[:-1] == sa[1:])
dups_vals = sa[np.append(np.diff(
np.insert((sa[:-1] == sa[1:]).astype(np.int8), 0, 0)
) == 1, False)]
print('has dups:', has_dups, ', dups values:', dups_vals)
Output is same:
has dups: True , dups values: [1 5 7 9]
And another even simpler numpy
solution:
import numpy as np
l = [1,4,5,6,7,8,9,9,1,5,7,7]
vals, cnts = np.unique(l, return_counts = True)
has_dups = np.any(cnts > 1)
dups_vals = vals[cnts > 1]
print('has dups:', has_dups, ', dups values:', dups_vals)
Also just checking if there are any duplicates can be done using simple next code with set()
:
l = [1,4,5,6,7,8,9,9,1,5,7,7]
has_dups = len(set(l)) < len(l)
print('has dups:', has_dups)
outputs
has dups: True