assignment statements: lists vs. strings

Duncan Booth me at privacy.net
Mon Feb 2 11:07:01 EST 2004


klaus_neuner82 at yahoo.de (Klaus Neuner) wrote in 
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)
>>>> list1
> [1, 2, 1]
>>>> list2
> [1, 2, 1]
>>>>
> 

You aren't comparing like with like here. You can do exactly the same as 
your string example using a list:

>>> list1 = [1,2]
>>> list2 = list1
>>> list1 = list1 + [3,4]
>>> list1
[1, 2, 3, 4]
>>> list2
[1, 2]
>>> 

The difference is that addition of strings, or lists, or anything else, 
creates a new object. The append method of the list type modifies an 
existing object. The string types don't have an append method because they 
are IMMUTABLE: immutable objects, once created never change their values.
Mutable objects can change their values.

Remember that assignment always creates another reference to an existing 
object, it never makes a copy of an object.

Builtin immutable objects include: int, long, float, str, unicode, tuple
Builtin mutable objects include: list, dict



More information about the Python-list mailing list