Skip to content
Advertisement

Subtract specific value from a list (of numbers) by user input

I’m a begginer in Python and i’m trying to do a program when the user chooses a number from a list, then after you type by how you much want to reduce this chosed number and then print the list.

I know that using list[specific index], check if matches with user input and repeating over and over again would do the job, but would be so unoptimized (if there’s a way to do this in a single line would be fine), I want to do something that automatically finds the the number of the list by the user input.

Desired Output:

[5, 10, 15, 20]
what number you want from the list?
> 15
by how much you want to subtract?
> 6
>> [5, 10, 9, 20]

my code:

list = [5, 10, 15, 20]
print(list)
number = int(input("what's the number you want from the list?"))

if number in list:
    print("by how much you want to subtract?")
    remove = int(input())
    list[number] = list[number] - remove
    print("Done It!")

else:
    print("not a valid number")

print(list)

Advertisement

Answer

You cannot access the number from list using itself. You must access it using its index. In order to get the correct index, use list.index(number).

Now, do not shadow list by creating a variable of that name. If you need a variable to represent a list, call it something else such as numList. If you shadow (aka assign a new value to overwrite a variable which is already in use), you will not be able to use the list’s constructor later on inside your application.

numList = [5, 10, 15, 20]
print(numList)
number = int(input("what's the number you want from the numList?"))

if number in numList:
    print("by how much you want to subtract?")
    remove = int(input())
    index = numList.index(number)
    numList[index] = numList[index] - remove
    print("Done It!")

else:
    print("not a valid number")

print(numList)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement