One way is to use the structure collections.Counter
:
from collections import Counter
lista = [4, 2, 1, 6, 1, 4, 4]
contador = Counter(lista)
repetidos = [
item for item, quantidade in contador.items()
if quantidade > 1
]
quantidade_repetidos = len(repetidos)
print(f'Há {quantidade_repetidos} números repetidos na lista')
See working on Repl.it | Ideone | Github GIST
The exit will be:
Há 2 números repetidos na lista
The Counter
basically defines a dictionary where the key will be the values of the list and the respective value the amount of times it appeared in the original list; thus, just filter the elements that have quantity greater than 1.
But this way you will create a new instance of
Counter
with each iteration; and will modify the input list, which is not a good idea as it may generate side effects.– Woss