I am trying to create a sketch of deleting items from a list. The data that will be deleted is the input() that will determine

Asked

Viewed 58 times

-2

objetos = ["1", "2", "3","4", "5", "6"]

escolha_cliente = input("ESCOLHA OS ITENS OU DIGITE FIM PARA NAO ESCOLHER 
NENHUM: ")
if escolha_cliente.isdigit():
    escolha_cliente = int(escolha_cliente)

if escolha_cliente == "fim":
    print("FIM!")

if escolha_cliente in objetos:
    del(objetos[escolha_cliente])

print(objetos)
  • If you have a list of strings, never your condition escolha_cliente in objetos will be satisfied, since escolha_cliente will be a int.

  • What should I do in this case? I just replaced it with Slice...

  • What do you want to do? If the user type 3, what should be the result?

  • The result should return the list "objects", but without the 3, in this case.

  • But which 3? The value 3 or the position 3?

  • Value 3, position 2

Show 1 more comment

1 answer

1

Take a look at lists and the difference between pop, remove and del. Here, for example.

In your case, as Voce wants to remove from the list by value selected, then you must use the remove...

Follow a basic example:

objetos = ["1", "2", "3","4", "5", "6"]
print(objetos)

escolha_cliente = input("ESCOLHA OS ITENS OU DIGITE FIM PARA NAO ESCOLHER NENHUM: ")
escolha_cliente_string = str(escolha_cliente) # Não é necessário fazer o cast para String
print(escolha_cliente_string)

objetos.remove(escolha_cliente_string)
print(objetos)

Remembering that remove will only remove the first found element, that is, if you have more than one, the others will remain in the list.

Also, I made no treatment for the case where the user enters a value that does not exist in the list.

  • 1

    Note: convert. escolha_cliente for str is unnecessary since the return of input at all times is a string.

  • Truth @Woss, my mistake

  • Thank you @Woss and @Vinicius!!

Browser other questions tagged

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