-   Programming (
-   -   Changing one element of a 2-D list in python (

Adwat 06-05-2012 07:16 PM

Changing one element of a 2-D list in python
I have the following code:


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:


What needs to be done if I just want to change one of the element?

Thanks for the help!

evo2 06-05-2012 10:06 PM


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:

a = [ [0]*2 for i in range(3) ]

colucix 06-06-2012 06:36 PM

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 05:01 AM.