Sunday, March 28, 2010

Python reference management

I ran into a crazy Python reference management behavior today. I wanted to do

x=y=[None for i in xrange(10)]

and then add elements to both x and y separately. Basically, wanted to avoid creating an empty list and then append stuff to each. No particular reason, just for the heck of it.

Turns out there is some kind of weird reference management policy in Python, which it so happens that I don't have the time to dive into right now. What this does is that it couples x to y, in such a way that changing elements of one affects the other.

So, the solution is to change the above line into

x=[None for i in xrange(10)]
y=[None for i in xrange(10)]

No comments: