[Tutor] Linked List

Alan Gauld alan.gauld at freenet.co.uk
Sun Mar 6 01:04:56 CET 2005

> >>> myls=range(50)
> >>> for i in myls:
> print i
> if i==20:
> myls.insert(5,5)
> The point is, the list(both size and elements) is
> changing even as it is being operated upon.

You are quite right it is, in general a bad idea to alter 
the thing you are iterating over.

> This particular case goes into infinite loop at i=20.

For obvious reasons: you insert something before 20 which 
moves up one position, the next element in the list is 
now 20 again.

Better to use a while loop over the indices if you must 
do this kind of thing, then increment the index as well 
as insert the item.

myls = range(50)
index = 0
while index < len(myls):
   print myls[index]
   if myls[index] == 20:
      index += 1
   index += 1

But if the changes are being made outside your loop (eg by 
another thread - dangerous practice anyway!) you need the 
linked list approach and you also need to treat our list 
as a protected resource in your threads. ie lock it before 
using otherwise you may wind up deleting the thing you are 
working on!


Alan G.

More information about the Tutor mailing list