How to know in Python if the elements in a list are different?

2

I want to know how I can do to verify that the elements of a list are all different (none repeated).

Ex:

lista=[1,-1,1,3,9,5]
codigo_verificador()

Exit:

True # Hay un elemento repetido

How can I know that there are repeated elements? Now try using a code like this:

The letters are numbers that the user puts

 lista = [a, b, c, d, e, f, g, h]
 if ar != br and br!=cr and cr!=dr and dr!=er and er != fr and fr!=gr and 
 gr!=hr and ass!=bs and bs!=cs and cs!=ds and ds!=es and es!=fs and fs!=gs and 
 gs!=hs:
 print("Todos son diferentes")

But still it does not come out: c

    
asked by Sebastian Mora 13.10.2018 в 03:02
source

2 answers

5

That 'a' is not equal to 'b' and that 'b' does not equal 'c' does not mean that 'a' does not equal 'c'. Doing all the possible comparisons in the list in that way does not scale, and as soon as the size of the list changes it will no longer work.

A very simple solution is to convert your list into a set, in which there can not be repeated values. Compare the size of your list with the set and if they are the same, they are all different.

lista=[1,-1,1,3,9,5]
if len(lista)==len(set(lista)): # False porque hay dos '1'
    print 'Todos son diferentes'
    
answered by 13.10.2018 / 04:12
source
0

Alternatively to the option given by the partner javdr you can use loops for nested, where the first for go through elements of the list, and in the second for that goes comparing them with the elements of the first for , to understand it better, I exemplify:

numeros = [1,-1,1,3,9,5]
def comparar(lista):
    indice_c = -1   # Se asigna a 0 para que no de error al comparar el index en el for
    for elemento in lista:
        indice_c = -1
        indice = lista.index(elemento)  # Se asigna el numero de indice del elemento a comparar
        for comparacion in lista: # Se toma el elemento a comparar
            indice_c += 1
            if indice_c == indice: # Esto es para evitar que se confunda el programa y compare un
                                   # elemento consigo mismo, lo cual no tendria sentido

                continue # Se reinicia el bucle
            elif elemento == comparacion: # Si el elemento de la lista es igual al elemento 
                                          # comparado, se retorna un False
                return False
    return True # De no haber elementos iguales, se retorna un True
print (comparar(numeros))

Output with repeated element

# numeros = [1,-1,1,3,9,5]
False

Output, now without repeated element:

# numeros = [1,-1,3,9,5]
True

If you do not understand, you can use Visual Studio Code to debug the code and view the variables in real time.

Clearly, the option that gave you javdr is much more simple and elegant , but I give you this alternative anyway.

Regards

    
answered by 13.10.2018 в 06:33