-1

How do I get my code to remove the value instead of removing the index?

availableNumbers= [
1, 2, 3, 4, 5, 6
]

numberOne = int(input("Choose your first number: "))
numberTwo = int(input("Choose your second number: "))

if numberOne in availableNumbers and numberTwo in availableNumbers:
del availableNumbers[numberOne: numberTwo]

print(availableNumbers)

So if 1 and 2 was inputted, 1 and 2 would be removed not 2 and 3

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • indent your code after the `if` block – raiyan22 Feb 04 '22 at 16:15
  • 1
    If you just want to remove the *first* occurrence you can use `availableNumbers.remove(numberOne)`. – BTables Feb 04 '22 at 16:17
  • Does this answer your question? [Is there a simple way to delete a list element by value?](https://stackoverflow.com/questions/2793324/is-there-a-simple-way-to-delete-a-list-element-by-value) – BTables Feb 04 '22 at 16:17
  • It might be worth clarifying: Are you trying to remove just the inputted values, or use them in a slice to remove all numbers between them as well? – G. Anderson Feb 04 '22 at 16:20

3 Answers3

2

I believe the function to do so is the remove function. Code:

availableNumbers= [
1, 2, 3, 4, 5, 6
]

numberOne = int(input("Choose your first number: "))
numberTwo = int(input("Choose your second number: "))

if numberOne in availableNumbers and numberTwo in availableNumbers:
    availableNumbers.remove(numberOne)
    availableNumbers.remove(numberTwo)

print(availableNumbers)
Anshumaan Mishra
  • 1,349
  • 1
  • 4
  • 19
  • 1
    It would be better if you can also explain why `remove` in this case is better than `del`. `remove` helps in removing the particular element(in this case `numberOne` and `numberTwo`). `del` helps in removing acc. to `index`. – Abhyuday Vaish Feb 04 '22 at 16:44
0

use the .remove() list method

availableNumbers = [1, 2, 3, 4, 5, 6]

numberOne = int(input("Choose your first number: "))
numberTwo = int(input("Choose your second number: "))

if numberOne in availableNumbers and numberTwo in availableNumbers:
    availableNumbers.remove(numberOne)
    availableNumbers.remove(numberTwo)

print(availableNumbers)

.remove() will remove the first matching value in a list, so if you have duplicates, it won't remove both

imbes
  • 71
  • 1
  • 6
0
availableNumbers.remove(numberOne)
availableNumbers.remove(numberTwo)

del is equivalent to pop which removes an item according to the index, use remove to remove it according to its value