assignment statements: lists vs. strings

Dang Griffith noemail at noemail4u.com
Mon Feb 2 11:29:14 EST 2004


On 2 Feb 2004 07:50:01 -0800, klaus_neuner82 at yahoo.de (Klaus Neuner)
wrote:

>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)
>>>> list1
>[1, 2, 1]
>>>> list2
>[1, 2, 1]
>>>>
Strings are immutable, lists are mutable. String concatenation builds
a new string object.  List appending does not build a new list.
Variables/names are references to objects; they are not themselves the
objects.

In the first example, you point both variables/names to the "bla"
string.  You then build a new string object "blabla" and point the
string1 variable to that new string.  string2 still points to the old
one.

In the second example, you point two variables/names to the [1, 2]
list.  You then append an item to that list.  The two variables still
point to the same list, which now has an additional element.

The "what is it good for" is the mutable/immutable difference.  Think
of it this way--numbers are immutable.  If you said:
>>> n1 = 3
>>> n2 = n1
>>> n1 = n1 + 1
>>> print n1, n2
You wouldn't expect the number 3 itself to change.  When you add n1 to
3, a new object with the value 4 is created and n1 is reassigned to
point to it.  Just as with the string, n2 still points to the "old" 3
object.
    --dang
p.s.
This last bit about the numbers is supposed to be conceptual, rather
than a description of the internal implementation.



More information about the Python-list mailing list