Replace blank data in a list (Python)

Asked

Viewed 563 times

0

I have a list that will receive input data and make a for loop to go through the list to find empty strings to replace them.

I’ve tried to use lista.remove() and lista.append(), but the value that would replace the blank string goes to the bottom of the list. The closest I came to solving the problem was using lista.index() as the example below shows, but it returns me the following error :

Exception has occurred: Typeerror 'str' Object cannot be Interpreted as an integer

lista = []

variavel_1 = lista.insert(0,input('entre com um numero:' ))
variavel_2 = lista.insert(1,input('entre com o segundo numero:' ))

for item in lista:
    if item == '':
        print(lista)
        index = lista.index('')
        insert = lista.insert("{}".format(index),input("digite o novo numero: "))
        print(lista)

How do I identify the position that is blank?

1 answer

1


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.

  • 1

    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

  • I used the list.remove() even. I confused. Thanks too much guy!

Browser other questions tagged

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