[Tutor] List indexing problem
steve at alchemy.com
Sat Jul 26 01:03:58 CEST 2008
Mike Meisner wrote:
> I need to do some statistical analysis by binning values into an array.
> Being new to Python, I tried to use a list of lists. I've extracted
> just the minimum code that I'm having trouble with:
What you need to remember is that Python works with *objects*, and
variables are simply *references* to those objects. So if I say
a = [1,2,3]
b = a
b and a both refer to the *SAME* list object (not two lists which happen
to have the same elements).
> temp = [[0, 0, 0],[0, 0, 0],[0, 0, 0]]
temp now refers to a list object containing 3 lists, each containing 3
> # initialize to zero
> for i in range(20):
Now IP contains 20 copies of references to the *same* list object.
So you were modifying the underlying list object which happens to be
referenced many times in IP.
More information about the Tutor