A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from http://mail.python.org/pipermail/python-list/2005-September/300674.html below:

Unexpected Behavior Iterating over a Mutating Object

Unexpected Behavior Iterating over a Mutating ObjectScott 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

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4