assignment statements: lists vs. strings

Karl Pflästerer sigurd at
Mon Feb 2 19:41:13 CET 2004

On  2 Feb 2004, Klaus Neuner <- klaus_neuner82 at wrote:

> 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?

Strings are immutable and lists are mutable objects.

>>>> string1 = "bla"
>>>> string2 = string1
>>>> string1 = string1 + "bla"

Here you create a new string string1 which is fresh allocated.
>>>> string1
> 'blabla'
>>>> string2
> 'bla'

If you did `id(string1)' and `id(string2)' before and after the
assignment you would have that after the assignment you had two
different objects.

>>>> list1 = [1,2]
>>>> list2 = list1
>>>> list1.append(1)

Here you modify an existing list in place.  But that's not the same as
you did with your string exapmle.  With a string you couldn't do that
since a string is immutable.

If you had written list1 = list1 + [1] you would have had a new list

>>> L1 = [1,2]
>>> L2 = L1
>>> id(L1)
>>> id(L2)
>>> L1 = L1 + [1]
>>> id(L1)
>>> id(L2)
>>> L2
[1, 2]
>>> L1
[1, 2, 1]


If you have nothing to say on a subject, replying with a line such as,
"I agree with this." puts you in the TO:'s for all future messages, and
establishes you as "one who really cares", if not an actual expert, on
the topic at hand.         -- from the Symbolics Guidelines for Sending Mail

More information about the Python-list mailing list