mutable list iterators - a proposal
Raymond Hettinger
python at rcn.com
Thu Apr 22 17:15:23 EDT 2004
[Raymond]
> > All the contortions in the code still suggest to me that the use case
> > needs a different algorithm. Try rewriting it with separate input and
> > output lists. My bet is that the code is clearer and more
> > maintainable.
[Jess Austin]
> My original use case was 3 classes in 30 lines, not including the
> subclassing of list.
Depending on your application, there may be a good alternative to
mutating in-place while iterating. Consider using a Queue object or
something similar (collections.deque in Py2.4, deque objects on ASPN,
or lists with append() and pop(0)):
while inputlist:
datum = inputlist.pop(0)
[processing with the element]
if somecondition:
inputlist.append(datum)
else:
continue # effectively removing the element
The idea is to get around the issues of mutating in-place by removing
the element in question, processing it, and if needed again, adding to
the end of the queue.
The ASPN recipes on queues show show to do this a bit more efficiently
than with the list object but the idea is the same.
> I love to use it. Iterators and list comprehensions were good, but
> coupled with itertools they are great.
>
> Thanks, Raymond, for all you've done for Python.
Thanks for the accolades.
Raymond
More information about the Python-list
mailing list