[Tutor] sorting in python

Kermit Rose kermit at polaris.net
Mon Jun 12 17:26:33 CEST 2006


  
Message: 6
Date: Mon, 12 Jun 2006 05:59:16 -0400
From: Kent Johnson <kent37 at tds.net>
Subject: Re: [Tutor] assignment statements in python
 
Actually sorting doesn't require copying the values in the list, it just
requires moving values to different locations of the list.
 
 
*****
 
Yes.  I wish to know how I can , for examplem,
 
given 
B = [1,2,4,5],
 
move B[3] to a  position of newly created B[4],
move B[2] to position of B[3]
Assign value 3 to position B[2].
 
That is,  I wish to insert the value 3, into it's sorted place within the
already sorted list B.
 
****
 
>>>>>
 
A list element is somewhat like a name - it is a reference to a value,
not a container for a value.
 
If you say
a=[1,2,3]
B=a
 
then a and B refer to the same list. Likewise, if you say
x=[ [1,2,3], [4,5,6] ]
x[1] = x[0]
 
then x[1] and x[0] refer to the same list.
 
 
***
>>> x = [ [1,2,3],[4,5,6]]
>>> x
[[1, 2, 3], [4, 5, 6]]
>>> x[1] = x[0]
>>> x
[[1, 2, 3], [1, 2, 3]]
>>> 
 
Needed to make sure I understood what would happen.
 
Does the value [4,5,6] get erased at this point?
 
 
********
 
 
 
 If you want x[1] (or B) to
refer to a new list, you have to copy the old list:
x[1] = x[0][:]
 
list[:] is the slice of the list that goes from the beginning to the end
- a copy.
 
 
*****
 
I missed the significance of the [:] slice until you explained it.
 
 
So, now I could write my code as
 
 
#  to insert 3 between 2 and 4 in 
 
B = [1,2,4,5]
 
B.append(B[3:3])
 
# I expected B[4] to have the value 5 at this point. 
# It is empty.   Why?
#  So, I compensate by making the next line
 
B[4] = B[3:3]
 
# B[4] is still an empty list.   Why?
 
# I try 
 
B[4] = B[3]
 
#  That seemed to work.
 
 
B[3] = B[2]
 
# Now I try
 
B[2] = 3
 
 
That worked.
 
However, I don't see the difference between this code,
 
and what I had before that did not work.
 
 
 
Kermit  <  kermit at polaris.net  >
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Kent
 
 



More information about the Tutor mailing list