[Tutor] List-question

Ed Singleton singletoned at gmail.com
Mon Dec 19 14:10:21 CET 2005


On 19/12/05, Ed Singleton <singletoned at gmail.com> wrote:
> On 19/12/05, Øyvind <python at kapitalisten.no> wrote:
> > I have one function that finds some values. Then I want that function to
> > find new values based on the values it found first. However, by just
> > looping, it starts on an eternal job.
> >
> > As illustrated in:
> > >>> list = [1,2,3]
> > >>> list2 = list
> > >>> list2
> > [1, 2, 3]
> > >>> for i in list:
> > ...     print i
> > ...     list2.append(4)
> > ...
> > 1
> > 2
> > 3
> > 4
> > 4
> > 4 and it will forever continue with 4's.
> >
> > Why would list be expanded with the values of list2? How can I copy the
> > result from one list, and do things with the list without getting it to
> > expand?
>
> Because they point to the same thing.
>
> Type "list2 is list" after your other code and see.
>
> You want list2 to be a COPY of list not a pointer to it.  Do this by using
>
> list2 = list.copy()
>
> Slices create a copy, so a shortcut is:
>
> list2 = list[:]

Sorry, you need to:

from copy import copy

before you can use copy.

Also, you shouldn't use "list" as a variable name. as it is a built-in
function that converts things to lists.  Use "list1".

That way you can also use list2 = list(list1).

Ed


More information about the Tutor mailing list