2.3 list reverse() bug?

Erik Max Francis max at alcyone.com
Thu Dec 25 06:12:15 EST 2003


Mark Carter wrote:

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

It's been that way since the very early versions of Python.  The
.reverse method modifies the list object in place, and "assignment"
merely creates another name for the same object.  In fact, .reverse's
return value of None is intended to signal exactly this to you.  After
all, does this surprise you:

>>> a = [1, 2]
>>> b = a
>>> b.append(3)
>>> a
[1, 2, 3]
>>> b
[1, 2, 3]

If it does, then you need to read the Python tutorial on how Python
deals with mutable objects.

-- 
 __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
/  \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
\__/ Nothing spoils a confession like repentence.
    -- Anatole France




More information about the Python-list mailing list