[Tutor] Linked List
Shitiz Bansal
shitizb at yahoo.com
Sun Mar 6 00:01:34 CET 2005
Got ya, it doesnt however help in my case as inside
the for loop also i intend to change the list
elements.
--- Kent Johnson <kent37 at tds.net> wrote:
> 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
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
__________________________________
Celebrate Yahoo!'s 10th Birthday!
Yahoo! Netrospective: 100 Moments of the Web
http://birthday.yahoo.com/netrospective/
More information about the Tutor
mailing list