1

Possible Duplicate:
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)]
Community
  • 1
  • 1
Derek
  • 818
  • 7
  • 11
  • 22

2 Answers2

2

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
Rakesh
  • 4,264
  • 4
  • 32
  • 58
  • 1
    You could also use a list comprehension for this (if you see the question I marked this as a duplicate of) – GWW Sep 05 '11 at 16:40
0

Or modify in place like this:

import datetime

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 i in range(len(list_dates) - 1, -1, -1):
    item = list_dates[i]
    if item > datetime.date(2012,1,1):
        del list_dates[i]

print list_dates

or

import datetime


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)]

i = 0
while i < len(list_dates):
    item = list_dates[i]
    if item > datetime.date(2012,1,1):
        del list_dates[i]
    else:
        i += 1

print list_dates
warvariuc
  • 57,116
  • 41
  • 173
  • 227