Tuesday, April 10, 2012

python initializers

I just got bitten by this, so let's share. I wanted to be lazy about initializing an array of 250 by 250 values and wrot e cache = [[-1]*250]*250. This unfortunately gave the wrong results later on, because the inner arrays are just pointers to one object, thus all 250 arrays inside are the same. Try for yourself

>>> a = [[0]*2]*2
>>> a
[[0, 0], [0, 0]]
>>> a[0][1] = 1
>>> a
[[0, 1], [0, 1]]

Conclusion:
Be very careful when using these "new" lazy style initializers!

No comments:

Post a Comment