Michael Welle wrote: > I want to create an iterator it=iter(list) and control a for-loop with > it. Is it save to append elements to the list in the body of the > for-loop or is the behaviour undefined then? PEP234 notes that once the > iterator has signaled exhaustion, subsequent calls of next() should not > change that state. That suggests that it is possible to modify the list > during the iterator's livetime.
It's possible, but usually not a good idea. Especially inserting or deleting elements before the current position of the iterator (you can think of it as an index into the list) gives results that are usually unexpected: >>> items = [1, "remove me", 2, "remove me", "remove me", 3, 4] >>> for item in items: ... if item == "remove me": ... items.remove(item) ... >>> items [1, 2, 'remove me', 3, 4] Pro tip: don't do it even when it's possible. > Ex.: > > foo = [1,2,3,4] > it = iter(foo) > > for e in it: > if e % 2 == 0: > x.append(e) I don't see how the example is related to the question. Did you mean foo.append(e) ? With that modification the loop would run "forever" because you keep appending items that satisfy the condition e % 2 == 0. > it = iter(foo) Normally you would just iterate over foo; the only use-case where you'd create an iterator explicitly is when you want to skip some items: it = iter(items) for e in it: if skip_next(e): next(it) -- https://mail.python.org/mailman/listinfo/python-list