E.Nurminski wrote:
> Hello to all good people
> 
> I am new to the great Py so am quite puzzled by the following code
> 
> ---------------
> 
> res = []
> x = [ 1, 1 ]
> for i in xrange(0,5):
>       res.append(x)
>       x[1] = x[1] + 1
>       print "x = ", x
>       print "res = ", res
> 
> ---------------
> 
> Looks like it puts smth like reference to 'x' into 'res' list, instead of 
> value. But if I want a value should I use a different method or what ?
> 
> Evgeni
> 
> P.S. Could not easily find the issue in the manual/tutorial can you point 
> me out to smth relevant ?
> 

Yes the same reference gets added every time.

res = []
x = [1, 1]
for i in xrange(0,5):
   newx = x[:]                 # copy the x
   res.append(newx)            # append the copy
   newx[1] += 1                # shorthand
   print "newx = %s" % newx    # basic formatting
   print "res = %s" % res      # should be what you expect

James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to