On 10/1/12 2:40 AM, Justin C. Walker wrote:

On Oct 1, 2012, at 00:28 , Santanu Sarkar wrote:

I have written the following:

T=[0]*2
S=[]
l=2
for i in range(l):
    T[0]=i
    T[1]=i+1
    print T
    S.append(T)

Now S becomes [[1, 2], [1, 2]] instead of [[0,1],[1,2]].
In my situation, length l of S is not fixed. Is there any
method to solve this problem?

This is the result of a feature of the Python language.  'T' is the name of an array, and 
acts like its address, so as you append T to S, you are continually reusing that same 
address.  When you update the elements in T (by, e.g., "T[0]=i"), you are 
modifying the content of T.

To avoid this, you could do something like

S=[]
l=2
for i in range(l):
     print T
     S.append([i,i+1])

For this example, you don't even really need T:
l=2
S = [[i,i+1] for i in range(l)]

Jason


--
You received this message because you are subscribed to the Google Groups 
"sage-support" group.
To post to this group, send email to sage-support@googlegroups.com.
To unsubscribe from this group, send email to 
sage-support+unsubscr...@googlegroups.com.
Visit this group at http://groups.google.com/group/sage-support?hl=en.


Reply via email to