for loop ignores some elements of my list
Question: > **Possible Duplicate:**  
>  [Remove items from a list while iterating in
> Python](http://stackoverflow.com/questions/1207406/remove-items-from-a-list-
> while-iterating-in-python)

I want to remove all the dates in a list which are later than a given date. I
can't see why my method only removes some items of the list. Here's what I've
got:

    
    
    import datetime
    import numpy as np
    import os
    
    list_dates = [datetime.date(2012,1,3), datetime.date(2012,1,1), datetime.date(2012,1,5), datetime.date(2013,1,3), datetime.date(2013,1,1)]
    
    for item in list_dates:
        if item > datetime.date(2012,1,1):
            list_dates.remove(item)
    
    print list_dates
    

returns

    
    
    [datetime.date(2012, 1, 1), datetime.date(2013, 1, 3)]
    


Answer: James and GWW are right, you cant modify the list while you are iterating
through the same. Instead copy the items which you want to keep to a new list.

    
    
    list_dates = [datetime.date(2012,1,3), datetime.date(2012,1,1), datetime.date(2012,1,5), datetime.date(2013,1,3), datetime.date(2013,1,1)]        
    
    for item in list_dates:
                if item < datetime.date(2012,1,1):
                    new_list_dates.add(item); // move this item (which you want to keep) to a new list.
    
        print new_list_dates
    

