1

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
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user3257242
  • 11
  • 1
  • 1
  • 2

5 Answers5

4

Just use the remove method for lists:

 l = ["ab", "bc", "ef"]
 l.remove("bc")

removes the elment "bc" from l.

Dietrich
  • 5,241
  • 3
  • 24
  • 36
2

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

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)
Ifart Mitul
  • 188
  • 1
  • 8
  • 1
    Actually, it will not. `input` is very special in python, and the argument inside `input` is the prompt. You could run this in IDLE or any other REPL. – DarthCadeus Oct 04 '18 at 12:25
0
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)
s3cret
  • 354
  • 2
  • 10
Wwe
  • 1
0

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')
Bart Mensfort
  • 995
  • 11
  • 21