LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Changing one element of a 2-D list in python (http://www.linuxquestions.org/questions/programming-9/changing-one-element-of-a-2-d-list-in-python-948710/)

Adwat 06-05-2012 07:16 PM

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!

evo2 06-05-2012 10:06 PM

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) ]
Evo2.

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 11:35 PM.