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
1
  • Presumably speclistpatient_peter is a list of names, all strings? Commented Jan 31, 2014 at 12:30

5 Answers 5

4

Just use the remove method for lists:

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

removes the elment "bc" from l.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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)

1 Comment

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.
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')

Comments

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)

1 Comment

Welcome to StackoverFlow! Please try to markdown your code and explain about your code for further detail.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.