I want to do a list comprehension so that it gives me the same result with less code. what the code does is print the letters [ gatopercnj ] that is, with the first two for achievement it is ready [ 'g','a','t','o','p','e','r ','r','o','c','o','n','e'',j'',o'] is ready now stored in the variable called list_letters, I want it to store in the variable result only non-repeating words ['g','a','t:','o','p','e','r','c','n','j'] With the previous code I can execute it but now I want to perform a list comprehension to the code.
lista_palabras = ["gato","perro","conejo"]
lista_letras = [ ]
resultado = [ ]
for una_palabra in lista_palabras:
for una_letra in una_palabra:
lista_letras.append(una_letra)
#quiero una letra de la var lista_letras
for letra in lista_letras:
#si la letra no esta en la var resultado
if letra not in resultado:
#se agrega la letra a la var resultado
resultado.append(letra)
#solo se almacenan las letras que no esten en la variable y listo
print(resultado)
It can be done in one line and without list comprehensions!
And you get:
How does it work
First, all the words of are joined
lista_palabras
into a single string, using"".join(lista_palabras)
.Then that single resulting string (which would be
"gatoperroconejo"
) is passed toset()
. It is a set constructor. Sets are python data types that store elements without repetition (that is, if a piece of data was already in the set, it is not added again). The constructorset()
expects an iterable as an argument, and we're passing it a string, which is in effect an iterable. So itset()
iterates through each element of that string and adds it to the set.The resulting set from there already has the letters, without repetition, that you were looking for. The final step is to convert that result to a list. This final step could actually be skipped depending on what you intend to do with those letters later. A set is also iterable, and supports the operator
in
to tell if a letter is in it or not. What it doesn't support is the bracket syntax. For exampleconjunto[0]
, it is not useful to access the first element of the set, because the sets are not ordered in any way and therefore it makes no sense to talk about their first or last element.Performance Note
Checking to see if an element is already in a set is much faster than checking to see if it's in a list, because of the way sets are implemented. This makes the proposed solution much faster than the one you had in the question.
As a curiosity, the solution iterating with loops and lists takes about 4.33 µs to execute on that list of three words. The proposed solution with sets takes 0.86 µs
In lists with more words the difference would be even greater.
You can do it like this and you don't use "lista_letras"