2.3 list reverse() bug?

Paul Rubin http
Thu Dec 25 06:12:02 EST 2003


cartermark46 at ukmail.com (Mark Carter) writes:
> >>> 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 correct.  d1 and d2 are the same list, and list.reverse reverses
in place.  If you want d1 and d2 to be two separate lists, try

  d1 = [1,2]
  d2 = d1[:]    # makes a copy of d1
  d2.reverse()
  print d1




More information about the Python-list mailing list