[Tutor] Python oddity
Jeff Younker
jeff at drinktomi.com
Thu Feb 28 04:15:00 CET 2008
So the problem is that when I change bb, aa also changes even
though I don't want it to. Is this supposed to happen?
Yes
Names are handles for objects. Assignment binds
a name to an object. The same object can be
bound simultaneously to many names.
Python distinguishes between equality and identity, so
there are two comparison operators: '==' and 'is'. Objects
are equal if they have the same value (==) but they are
identical only if they refer to the same object (is).
The constructor expressions [], {}, and () produce
new objects.
>>> [1, 2] == [1, 2] # same value
True
>>> [1, 2] is [1, 2] # but different lists
False
>>> a = [1, 2] # this is assigned to a new list
>>> b = [1, 2] # this is also assigned to a new list
>>> a == b # the lists have the same value
True
>>> a is b # but they are not the same list
False
>>> a = [1, 2] # assign to a new list
>>> b = a # attach the list in a to a new name
>>> a == b # they have the same value
True
>>> a is b # because they are the same list
True
The list(FOO) function copies an list.
>>> a = [1, 2] # new list
>>> b = list(a) # make a copy of the list in b
>>> a == b # the original and copy are equal
True
>>> a is b # but they are not the same list
False
- Jeff Younker - jeff at drinktomi.com -
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080227/a0c42fb4/attachment.htm
More information about the Tutor
mailing list