deleting items within a for loop - mutable indices
Steven Rumbalski
srumbalski at copper.net
Sat Apr 24 22:09:28 EDT 2004
James Moughan wrote:
> you could speed either up for largish lists with hashing;
>
> dict = {}
> for d in deletion_list:
> dict[d] = 1
> tmp = [x[i] for i in range(len(x)) if not dict.has_key(i)]
> x = tmp
If order doesn't matter and the items are unique you may wish to use
sets.Set from python 2.3 instead of a dict:
>>> from sets import Set
>>> set = Set(['a', 'b', 2, 42])
>>> for item in deletion_list:
... set.discard(item)
...
>>> print set
Set(['b', 42])
--
Steven Rumbalski
news AT rumbalski DOT com
More information about the Python-list
mailing list