On Sat, Apr 12, 2008 at 04:52:06PM -0400, James Antill wrote:
You can't alter things that you are iterating, the easist fix is:
for directory in directories[:]:
...the others being to create a new list of just what you want, or a list of what needs to go and then do the .remove() calls on that (these methods can be worth it, for large lists).
Actually, I'd contend this technique gets worse as your list size increases. First, you're making a copy pass, doubling your memory footprint, and then a second pass to actually filter the list down to just the elements you want. That will get slower as your list size increases.
Oh, and that reminds me of another way, using the builtin filter():
directories = ['20080412', '20080324', 'blahblah', 'latest-dir',
'rawhide-20080410', 'rawhide-20080411', 'rawhide-20080412' , '20080401']
filter(lambda x: x.startswith('200'), directories)
['20080412', '20080324', '20080401']