assignment statements: lists vs. strings
Dan Bishop
danb_83 at yahoo.com
Mon Feb 2 15:34:50 EST 2004
klaus_neuner82 at yahoo.de (Klaus Neuner) wrote in message news:<3e96ebd7.0402020750.3b0b9b82 at posting.google.com>...
> Hello,
>
> I would like to understand the reason for the following difference
> between dealing with lists and dealing with strings: What is this
> difference good for? How it is accounted for in Python slang?
>
> Klaus
>
> >>> string1 = "bla"
> >>> string2 = string1
> >>> string1 = string1 + "bla"
> >>> string1
> 'blabla'
> >>> string2
> 'bla'
> >>>
>
> >>> list1 = [1,2]
> >>> list2 = list1
> >>> list1.append(1)
This is *not* equivalent to the string code. Notice that
>>> list1 = list1 + [1]
>>> list1
[1, 2, 1]
>>> list2
[1, 2]
*does* behave like your string example.
> >>> list1
> [1, 2, 1]
> >>> list2
> [1, 2, 1]
Unlike string1, the name "list1" hasn't been rebound since the
assignment "list2 = list1", and therefore they still refer to the same
object.
More information about the Python-list
mailing list