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 details, check the python documentation, in particular, the difference 
between copy() and deepcopy().

Maybe start here:
  <http://docs.python.org/library/copy.html#copy.deepcopy>

HTH

Justin

--
Justin C. Walker, Curmudgeon at Large
Director
Institute for the Enhancement of the Director's income
-----------
--
They said it couldn't be done, but sometimes,
it doesn't work out that way.
  - Casey Stengel
--



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