Return the number of repeated elements in a list

0

Good morning, could you help me with a question? How do I return the amount of elements that are repeated in a list in python? For example: A list = [4,2,1,6,1,4,4] should return the value 2 because there are two elements that are repeated in the list. Can anyone help me how?

    
asked by anonymous 24.05.2018 / 17:41

3 answers

2

You can do this natively by setting a set() to all elements that are repeated, and counting the number of elements in that set using len() :

lista = [ 4, 2, 1, 6, 1, 4, 4 ]

qtd = len( set( [ item for item in lista if lista.count( item ) > 1] ) )

print( qtd )
    
24.05.2018 / 19:52
0

One way is to use the collections.Counter structure:

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 at Repl.it | Ideone | GitHub GIST

The output 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 their value the amount of times it appeared in the original list; so, just filter the elements that have quantity greater than 1.

    
24.05.2018 / 18:12
0

In one function it looks great!

from collections import Counter


def remove_dups(l1, l2):
    for x in l1:
        l2.append(x)
        if Counter(l1)[x] == 1:
            l1.remove(x)


l1 = [1, 2, 1, 3, 4, 3]
l2 = []


remove_dups(l1)

print('Removed numbers ' + str(l1))
print(l2)
    
24.05.2018 / 22:01