newbe question about lists

Jason Stokes jstok at bluedog.apana.org.au
Sat Mar 4 20:22:47 EST 2000


Fredrik S wrote in message <0d6dde44.8e4c635f at usw-ex0102-015.remarq.com>...
>Sorry for this simple question, but I can't go to sleep before I
>have solved it.
>
>I am running python on Beos for the first
>time.
>
>I'm going through a study course online, and ringt now I
>am trying lists.
>
>I type the following:
>>>>
>l1=["a1","a2","a3"]
>>>> l2=["a4","a5","a6"]
>>>> l3=l1
>>>>
>l3[1:1]=l2
>>>> l3
>['a1', 'a3', 'a4', 'a2']
>>>> l1
>['a1', 'a3',
>'a4', 'a2']
>
>QUESTION:
>Why is value of l1 changed... The only
>thing I can think of is B U G ...


This is just standard reference semantics.  Lists are mutable structures,
first of all.  Assigning the first list to l1 creates the list object and
binds it to the name "l1".  Assigning l1 to l3 binds "l3" to the *same*
object.  Therefore, any changes in the object referred to by the "l1" name
are now reflected in the object referred to by the "l3" name, because they
are one and the same.

To prevent this behaviour bind l3 to a *copy* of the object referred to by
l1, like this:

>>>l3 = l1[:]







More information about the Python-list mailing list