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.
import copy
def main():
titles_list = ["English", "Math", "History", "IT", "Biology", "Spanish"]
titles_list_orig = copy.deepcopy(titles_list)
for title in titles_list_orig:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With