List iterator thread safety
Peter Otten
__peter__ at web.de
Thu Aug 27 08:41:07 EDT 2009
Emanuele D'Arrigo wrote:
> On Aug 27, 2:01 am, a... at pythoncraft.com (Aahz) wrote:
>> Well, I'm not sure about exceptions, but you almost certainly won't get
>> the results you want.
>
> What I'd like in this context is to iterate through the items in the
> list without processing the same item twice and without skipping item
> that are in front of the current iterator position. Somehow I can't
> quite prove to myself if this is possible or not over multiple
> threads. I.e. a dictionary will throw an exception about the object
> changing size while iterating through it. A list doesn't, hence the
> question.
This is not even possible in a single thread:
>>> items = [1, 2, 3]
>>> for i in items:
... print i
... if 1 in items: items.remove(1)
...
1
3
Basically a list iterator is just a list reference and an index into that
list. No effort is made to keep track of added or removed items.
Peter
More information about the Python-list
mailing list