[Tutor] Sort Output

Shantanoo Mahajan shantanoo at gmail.com
Wed Sep 17 21:41:36 CEST 2008


Solution 1:
 >>> a=[2,3,1,4]
 >>> b=a[:]
 >>> a
[2, 3, 1, 4]
 >>> b
[2, 3, 1, 4]
 >>> a.sort()
 >>> a
[1, 2, 3, 4]
 >>> b
[2, 3, 1, 4]
 >>>

Solution 2:

 >>> from copy import deepcopy
 >>> a=[2,1,3,4]
 >>> b=deepcopy(a)
 >>> a
[2, 1, 3, 4]
 >>> b
[2, 1, 3, 4]
 >>> a.sort()
 >>> a
[1, 2, 3, 4]
 >>> b
[2, 1, 3, 4]
 >>>

HTH.

regards,
shantanoo

On 18-Sep-08, at 1:00 AM, Wayne Watson wrote:

> I'm using Python 2.4 in Win XP. I was surprised to find the result  
> below.
>
> >>> a =[4,2,5,8]
> >>> b = a
> >>> a.sort()
> >>> a
> [2, 4, 5, 8]
> >>> b
> [2, 4, 5, 8]
>
> b no longer has the same value as it began. Apparently to prevent  
> sort from making it the same I have to resort to copying b into a  
> first? What is the proper way to retain a variable with the original  
> values of a?
> -- 
>            Wayne Watson (Watson Adventures, Prop., Nevada City, CA)
>
>              (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
>               Obz Site:  39° 15' 7" N, 121° 2' 32" W, 2700 feet
>
>             "Though no one can go back and make a brand new start,
> 	     ANYONE can start from now and make a brand new end."
> 		                    -- Anonymous
>
>                     Web Page: <www.speckledwithstars.net/>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080918/49fd4182/attachment.htm>


More information about the Tutor mailing list