strange append
Gary Herron
gherron at islandtraining.com
Mon Oct 2 01:29:22 EDT 2006
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 ?
>
It's best, in Python, to consider *everything* to be a reference to an
object. Most actions will work with a reference to an existing object,
and creating a new reference to an object will almost never create a
copy of the object. If you *do* want to create an object, you may
consider using the copy module:
http://docs.python.org/lib/module-copy.html
(But I must point out, that in 12 years of programming Python, I've
hardly ever used that module.)
Gary Herron
More information about the Python-list
mailing list