Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

problem Deleting list items in a for loop (python) [duplicate]

Tags:

python

loops

list

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
like image 205
RY4N Avatar asked Mar 23 '11 06:03

RY4N


1 Answers

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
like image 103
w00t Avatar answered Sep 27 '22 17:09

w00t