insertion sorts...

MRAB google at mrabarnett.plus.com
Tue Jul 1 00:35:14 CEST 2008


On Jun 30, 3:29 pm, python_newbie <serbule... at gmail.com> wrote:
> On 25 Haziran, 17:44, MRAB <goo... at mrabarnett.plus.com> wrote:
>
>
>
> > 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
>
> Thanks again. I see that you use two different syntax for lists
> "mylist = new_list" and "mylist[:] = new_list" these are same i
> think ?

The difference is that "mylist = new_list" makes mylist refer to the
same list as new_list:

    Before:

        otherlist ───┐
                     ├───► [1, 2, 3]
        mylist ──────┘

        new_list ────────► [4, 5, 6]

    After:

        otherlist ───────► [1, 2, 3]

        mylist ──────┐
                     ├───► [4, 5, 6]
        new_list ────┘

whereas "mylist[:] = new_list" modifies the list to which mylist
already refers to contain the same items as new_list:

    Before:

        otherlist ───┐
                     ├───► [1, 2, 3]
        mylist ──────┘

        new_list ────────► [4, 5, 6]

    After:

        otherlist ───┐
                     ├───► [4, 5, 6]
        mylist ──────┘

        new_list ────────► [4, 5, 6]

(I hope the characters come out OK! :-))



More information about the Python-list mailing list