[Tutor] basic lists and loops question

Kent Johnson kent37 at tds.net
Thu May 15 03:06:30 CEST 2008


On Wed, May 14, 2008 at 6:03 PM, Jon Crump <jjcrump at myuw.net> wrote:
> def events(data):
>  evts = []
>  for x in data:
>    for y in data:
>      if (x['placename'] == y['placename']) and (x['end'].month + 1 ==
> y['start'].month) and (y['start'] - x['end'] == datetime.timedelta(1)):
>        x['end'] = y['end']
>        data.remove(x)
>    evts.append(x)
>  return evts
>
> I understand about removing elements from a container you're iterating. Is
> data.remove(x) problematic in this context?

Yes. It can cause the iteration to skip elements ofthe list. Better to
post-process the list with a list comprehension:
evts = [ evt for evt in evts if 'processed' not in evt ]

Kent


More information about the Tutor mailing list