I want to remove an element from a list by using a user input and a for loop.
This is as far I got:
patientname = input("Enter the name of the patient: ")
for x in speclistpatient_peter:
del speclistpatient_peter
I want to remove an element from a list by using a user input and a for loop.
This is as far I got:
patientname = input("Enter the name of the patient: ")
for x in speclistpatient_peter:
del speclistpatient_peter
Just use the remove
method for lists:
l = ["ab", "bc", "ef"]
l.remove("bc")
removes the elment "bc"
from l
.
Use a list comprehension; altering a list in a for
loop while looping can lead to problems as the list size changes and indices shift up:
speclistpatient_peter = [x for x in speclistpatient_peter if x != patientname]
This rebuilds the list but leaves out the elements that match the entered patientname
value.
This line is incorrect:
patientname = input("Enter the name of the patient: ")
Putting anything in the input()
function rather than the specific thing you want to delete or find from the list will cause an error. In your case you added ("Enter the name of the patient: ")
, so after the execution it will search for "Enter the name of the patient: " in the list but its not there.
Here is how you can delete a specific item from the list. You don't have use loop, instead you can delete it by using the remove()
function:
print("Enter the item you want to delete")
patientname = input() # Dont Put anything between the first bracket while using input()
speclistpatient_peter.remove(patientname)
print(speclistpatient_peter)
print("Enter the item you want to delete")
patientname = input() # Dont Put anything between the first bracket while using input()
speclistpatient_peter.remove(patientname)
print(speclistpatient_peter)
To remove a certain element: speclstpatient_peter.remove('name')
If the array contains 2x the same element and you only want the firstm this will not work. Most dynamic is just a counter instead of a pointer:
x=0
while x<len(speclistpatient_peter):
if speclistpatient_peter[x].find(something): # or any if statement
del(speclistpatien_peter[x])
else:
x=x+1
or make a function to keep it readable:
def erase(text, filter):
return [n for n in text if n.find(filter)<0]
a = ['bart', 'jan']
print erase(a, 'rt')