Re: Lazy lists for use with large dictionaries

Guido.van.Rossum@cwi.nl
Thu, 29 Sep 1994 17:10:30 +0100

> Isn't the same true for lists also? The follwing will result in an
> endless loop (well, almost, limited by memory):
>
> list = [1,2,3,4]
> for l in list:
> list.append(5)

Eh, yes. Here the remedy is to iterate over a copy of the list:

list = [1,2,3,4]
for l in list[:]:
list.append(5)

The same efficiency considerations apply.

> What do you have in mind with trapping modifictions? I don't see an
> obvious way how to deal with that situation in general, i.e. iterating
> over a set of elements while the set is modified.

If iterators are objects, they can maintain an iterator count in the
object they are iterating over. The object can refuse modifications
if this count is zero.

--Guido van Rossum, CWI, Amsterdam <mailto:Guido.van.Rossum@cwi.nl>
<http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>