insertion sorts...

MRAB google at mrabarnett.plus.com
Wed Jun 25 10:44:50 EDT 2008


On Jun 25, 11:37 am, "A.T.Hofkamp" <h... at se-162.se.wtb.tue.nl> wrote:
> On 2008-06-25, python_newbie <serbule... at gmail.com> wrote:
>
> > On 24 Haziran, 04:33, Terry Reedy <tjre... at udel.edu> wrote:
> > Thanks for all answers. At the end i ve only one point. If a decide to
> > copy list to iterate when will i have to do this ? Before the
> > iteration ? And then iterate through one list and change value of the
> > other ?
>
> Before starting the iteration would be a good point....
>
> I usually do in such cases:
>
> for x in mylist[:]:
>    ...
>
> making a copy just before the for loop starts.
>
> Lately, I have started avoiding in-place modification of lists. Instead, I
> construct a new list from scratch inside the for-loop, and replace the old list
> with the newly constructed list afterwards like:
>
> new_list = []
> for x in mylist:
>    ....
>    new_list.append(x)
>
> mylist = new_list
>
> by appending a different value than the original or by not appending, you can
> influence the contents of the new list.
>
> I find this solution nicer than in-place modification of an existing list.
>
> Sincerely,
> Albert

And if you were originally doing in-place modification because there
were also other references to the list then you could just do:

mylist[:] = new_list



More information about the Python-list mailing list