Changing one element of a 2-D list in python
I have the following code:
a=[[0]*2]*3 print a a[1][1]=2 print a the output is: [[0,0],[0,0],[0,0]] [[0,2],[0,2],[0,2]] Why is it changing all the elements of the list? Shouldn't the output be: [[0,0],[0,2],[0,0]] What needs to be done if I just want to change one of the element? Thanks for the help! |
Hi,
this is because everything (except floats, ints etc) are references in python. Your 3 element array contains three references to the same two element array. Try declaring your array like: Code:
a = [ [0]*2 for i in range(3) ] |
Moved: This thread is more suitable in Programming and has been moved accordingly to help your thread/question get the exposure it deserves.
|
All times are GMT -5. The time now is 10:48 AM. |