2.3 list reverse() bug?
Bjorn Pettersen
bjorn.pettersen at comcast.net
Thu Dec 25 06:17:47 EST 2003
cartermark46 at ukmail.com (Mark Carter) wrote in
news:d3c9c04.0312250303.561b119d at posting.google.com:
> I did this:
>
> Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on
> win32
>
>>>> d1 = [1,2]
>>>> d2 = d1
>>>> d2.reverse()
>>>> print d1 #note: d1, not d2
> [2, 1]
>>>>
>
> Surely that can't be right: d1 should still be [1,2]. If it is
> "right", then I expect that many people are in for a suprise.
Nah, not really. Why do you expect d2 = d1 to make a copy of d1 before
assigning it to d2? (and if d1 contained nested lists, should it copy them
too or just make references to them?)
In Python, assignment binds a name on the left hand side, to the object on
the right hand side... period. There is no magic going on behind the
scenes.
In your example d2 and d1 are two names for the _same_ object, [1,2], which
means that any way you mutate the object through one name will be visible
when the object is accessed through the the other name.
There is a module called copy that let you get the semantics that you're
looking for. I've never used it in my 6+ years of Python programming, since
it normally indicates the presence of flawed logic <wink>.
-- bjorn
More information about the Python-list
mailing list