To replace the value just get the position of the element in the list and through the index, pass the new value that will be obtained through the input
. You even had a good idea, only you ended up creating a monster for something simple and erring on some things.
Understanding the Insert method and why the error was released...
First of all, this TypeError
is generated because you tried to use the method format
which only accepts Strings passing an integer value, which in this case is the index obtained.
The method insert
receives as parameter an integer value ( position of the element ) and the element that will be inserted in the list. Then the correct in this case would be the following code:
lista.insert(index, input("digite o novo numero: "))
Another very important detail is that this method does not return any value and also does not replace an element in the list. This method is more like a append
with the difference that you can determine a position where the element will be placed in the list.
Solving the problem...
So how can we replace the value in the list ? Just overwrite the element at the position x as in the example below:
# O for agora é utilizado com o range para percorrer
# todas as posições da lista sem utilizar o método index.
for index in range(len(lista)):
# Verifica se a string é vazia ou somente espaços.
if lista[index] == "" or lista[index].isspace():
novo_valor = input("Digite um novo número: ")
lista[index] = novo_valor # Sobrescreve o elemento na posição "index".
print(lista)
[ Extra ] Understanding the append method and how to remove values in list...
You said in your question that you had tried to use the method append
and that did not know why the new value go to the bottom of the list. The reason why this happens is because the append
is a method to add an element at the end of the list. As in the example below:
lista = []
lista.append("pizza")
lista.append("lasanha")
print(lista) # Saída: ["pizza", "lasanha"]
You also said you tried to use lista.delete
but I’m sure you got the error below because this method does not exist in list.
Attributeerror: 'list' Object has no attribute 'delete'
If you want to remove some value, you should use the method remove(valor)
or pop(indice)
. See the example below:
lista = ["pizza", "lasanha"]
lista.remove("lasanha") # Remove o elemento "lasanha".
lista = ["pizza", "lasanha"]
lista.remove(1) # Remove o elemento que está na posição 1 (no caso lasanha).
Man, thank you so much for the clear and objective response. I will test and give feedback.
– imaestri
I believe it is more interesting to keep the IF condition as
lista[index] == ''
otherwise your code will not accept that the user type zero, which is also a value falsy– fernandosavio
I used the list.remove() even. I confused. Thanks too much guy!
– imaestri