-2

Basically i want to make a program in python that, given a list of words and a list of letters, it will print out a list with only the words that don't contain any letter in the list of letters.

lista = ["computador","comida","atum","pai","porco","amigo","bloco","carro","banana","janela","calculadora","caneca","prato","livro","jogo","fabrico","cruz","pedra","ar","vento"]
letras_prib = ["a","b"]
for palavra in lista:
    for letra in letras_prib:
        if letra in palavra:
            listafinal = lista.remove(palavra)
print(listafinal)

Here you can see the list of words is:

lista = ["computador","comida","atum","pai","porco","amigo","bloco","carro","banana","janela","calculadora","caneca","prato","livro","jogo","fabrico","cruz","pedra","ar","vento"]

And the list of letters is:

["a","b"]

My problem is, when i run this exact program, it just prints out "None". From my understanding it should be printing out every word that does'nt contain the letter "a" or "b". I really need help as i've searched a lot but still have no idea how to fix this. PS: If you have trouble understanding some portuguese words;

palavra = word

lista = list

listafinal = finallist

letra = letter

letras_prib = prohibited letters.

And yes, there ARE words in the list that don't contain the letter "a" or the letter "b", like "porco" for example.

2 Answers2

1

.remove doesn't return a new list with the item removed, it removes it inplace and returns none

Instead, start your final list as a copy of the original and then just remove without assigning to a variable

listafinal = lista[:]  # When declaring listafinal
...
listafinal.remove(palavra)  # Where you're currently removing
Sayse
  • 42,633
  • 14
  • 77
  • 146
0

you can use del to remove element from the list. And while iterating through list iterate from the last so removing elements from last will remove all the elements. Check below code:

lista = ["computador", "comida", "atum", "pai", "porco", "amigo", "bloco", "carro", "banana", "janela", "calculadora",
         "caneca", "prato", "livro", "jogo", "fabrico", "cruz", "pedra", "ar", "vento"]
letras_prib = ["a", "b"]

for palavra in lista[::-1]:
    for letra in letras_prib:
        if letra in palavra and palavra in lista:
            del lista[lista.index(palavra)]
print(lista)
Amit Nanaware
  • 3,203
  • 1
  • 6
  • 19