Return the amount of elements repeated in a list

Asked

Viewed 3,331 times

0

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

3 answers

2

You can do this natively by riding a set() with all repeating elements, and counting the amount of elements in this 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 )

1

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.

0

In a 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)
  • 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.