Possible Duplicate:
Remove items from a list while iterating in Python
Hi im having a problem i cant seem to delete items whilst iterating through a list in python, Here is what i've got: a title should be removed if a user Inputs n or N when asked the question to delete in the for loop, the problem is that when its all done the items are all still there and none have been removed...
titles_list = ["English", "Math", "History", "IT", "Biology", "Spanish"]
for title in titles_list:
print "Do you want to keep the title:", title , "\n or Delete it ? Input Y for keep, N for Delete "
Question = raw_input()
if str(Question.upper) == "N":
titles_list.remove(title)
print titles_list
The below code will fix your issue. You have to iterate over a copy of the list. You can't remove items from the list you are iterating over.
I know there is an answer already, here is another way for completeness, and to demonstrate list comprehension.
This method takes a list, asks to keep each item, and returns a new list excluding the ones marked for deletion:
I think the main issue in your code was incorrect usage of upper function. Once you fix it, you can remove the titles from the list as you please. You can either use index or the value. Here is the code snipped that worked for me
Please see the commented lines using index. Also, you can make your code more concise using the raw_input(prompt) feature.
You also need to think about the scenario where there are multiple occurrences of the same titles in your list, in that case I suggest get all the indices for the title till the list is empty and delete the titles using del(index) as the solutions presented above will remove only the first occurrence of the title.
Your code actually has two major issues.
The first is that you are not calling the
upper
method, but merely referencing it. You need to actually call it (viaQuestion.upper()
) as w00t does in his answer.Putting some diagnostic print statements inside your loop would have been a good way to see that (especially printing out
str(Question.upper)
) (Tangent:Question
is a bad name for a variable that holds the answer to a question the program asked of the user)Secondly, removing already seen items from a list you're iterating over will result in skipping values. You don't actually need to copy the whole list to deal with that - just iterating over it in reverse is enough to fix the problem.
Finally, a couple of minor cosmetic points are that
raw_input()
accepts a prompt argument, so you don't need a separate print statement and callingupper()
on a string will itself always return a string: