This is my sample database:
In my script now, I am adding elements to the list with the following code:
import pandas data = pandas.read_excel("Sample database copy.xlsx") name = dict(zip(data["Abbreviation"],data["Name"])) list1 = [] incoming_msg = input('Please type what you want to add: ') incoming_msg = incoming_msg.split() # split the string by space if len(incoming_msg) == 2: # if there are two elements in the list (number and name) list1 += [name[incoming_msg[1]]] * int(incoming_msg[0]) else: list1.append(name[incoming_msg[0]])
So now if type “2 JO” my list will have two new elements “John” and “John”.
Now I want to do exactly the same but for eliminating objects of a list. I tried to replace the current operator “+=” for “-=” but surprisingly it is not working. Any ideas on how I could solve this?
PS. I need to do it all out of the same input. I cannot ask separately for key and quantity. I want to make a replication of the above code but for removing the objects.
Advertisement
Answer
You could use list.remove()
:
Remove the first item from the list whose value is equal to x. It raises a ValueError if there is no such item.
import pandas as pd data = pd.read_excel("Sample database copy.xlsx") name = dict(zip(data["Abbreviation"], data["Name"])) list1 = [] incoming_msg = input('Please type what you want to add: ') incoming_msg = incoming_msg.split() # split the string by space if len(incoming_msg) == 2: # if there are two elements in the list (number and name) list1 += [name[incoming_msg[1]]] * int(incoming_msg[0]) else: list1.append(name[incoming_msg[0]]) print('n'.join(list1)) incoming_msg = input('Please type what you want to delete: ') incoming_msg = incoming_msg.split() # split the string by space if len(incoming_msg) == 2: # if there are two elements in the list (number and name) num_to_remove = int(incoming_msg[0]) while name[incoming_msg[1]] in list1 and num_to_remove > 0: list1.remove(name[incoming_msg[1]]) num_to_remove -= 1 else: if name[incoming_msg[0]] in list1: list1.remove(name[incoming_msg[0]]) print('n'.join(list1))
Example Usage:
Please type what you want to add: 4 JO John John John John Please type what you want to delete: 2 JO John John