Unexpected Behavior Iterating over a Mutating Object

Scott David Daniels Scott.Daniels at Acm.Org
Tue Sep 13 19:23:23 EDT 2005


Dave Hansen wrote:
> ...
>>>>data = [ 'First', 'Second DEL', 'Third', 'Fourth',
> 	     'Fifth DEL', 'DEL Sixth', 'Seventh DEL', 'Eighth DEL',
> 	     'Ninth DEL', 'Tenth', 'Eleventh', 'Twelfth']
>>>>bfr = []
>>>>for item in data:
> 	if item.find('DEL') >= 0:
> 		bfr.append(item)
> 		data.remove(item)

assuming Python 2.4:

kept = []
for position, text in reversed(list(enumerate(data))):
     if 'DEL' in text:
         removed.append(text)
     else:
         del data[position]

This uses reversed so positions remain valid as the list is pruned.

--Scott David Daniels at Acm.Org
Scott.Daniels at Acm.Org



More information about the Python-list mailing list