[Tutor] Linked List

Kent Johnson kent37 at tds.net
Sat Mar 5 19:21:14 CET 2005


Shitiz Bansal wrote:
> I could not understand what you exactly mean.
> 
> In order to explain wat my problem is, here is an
> example code. Its not exactly what I am doing, I am
> using multiple threads and a rather complicated code
> so  try and understand the sense rather than the code
> itself.
> 
> 
>>>>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.

What Jacob is saying is, one common way to deal with this is to make a copy of the list and iterate 
over that while changing the original list. Your sample would look like this:

myls=range(50)
for i in myls[:]:  # <-- Note: makes a copy of myls
	print i
	if i==20:
		myls.insert(5,5)

Kent

> 
> This particular case goes into infinite loop at i=20.
> 
> Interestingly, I can freely edit the list yet to be
> traversed, without any ill effects, which would not
> have been possible if a python list was a pure
> array(due to immutable length of an array in c).
> 
> Shitiz
> 
> --- "Jacob S." <keridee at jayco.net> wrote:
> 
> 
>>I'm taking a shot in the dark and answering here.
>>
>>Have you tried making a copy of the list, iterating
>>over the copy, and 
>>changing the original based on the copy?
>>
>>Jacob



More information about the Tutor mailing list