assignment statements: lists vs. strings

Terry Reedy tjreedy at udel.edu
Mon Feb 2 17:25:05 CET 2004


"Klaus Neuner" <klaus_neuner82 at yahoo.de> 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:

You are doing different operations, and hence should not expect the same
result.


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

Here you add two strings together to get a third, which you bind back to
the first name

> >>> string1
> 'blabla'
> >>> string2
> 'bla'

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

Here you mutate a list in place, which you can do because lists are mutable
and which you cannot do with strings.  To parallel your string operation,
try

list1 = list1 + [1,2]

before you mutate list1 and you should get [1,2,1,2]


> >>> list1
> [1, 2, 1]
> >>> list2
> [1, 2, 1]

Terry J. Reedy







More information about the Python-list mailing list