0

I have the following piece of code

>>> no=[]
>>> matrix = [[[] for x in xrange(4)] for x in xrange(4)] 
>>> no=[2]
>>> temp = no
>>> matrix[1][2].append(temp)
>>> no.append(3)
>>> matrix[1][2]

when I print matrix[1][2] I am getting the following output:

[[2, 3]]

But what I want is:

[2]

So basically what is happening is the list is getting changed inside the matrix list if I change it afterwards. But I don't want to get it changed

How can I do it ? And why is it happening ?

James Mertz
  • 8,459
  • 11
  • 60
  • 87
user2823667
  • 193
  • 2
  • 18

1 Answers1

3

Make a copy of no temp = no[:].

temp = no is just a reference to the same object so any changes in no will affect temp

A reference:

In [21]: my_l = [1,2,3]

In [22]: ref_my_l = my_l

In [23]: ref_my_l
Out[23]: [1, 2, 3]

In [24]: my_l.append(4)

In [25]: my_l
Out[25]: [1, 2, 3, 4]

In [26]: ref_my_l
Out[26]: [1, 2, 3, 4]

A copy:

In [27]: my_l = [1,2,3]

In [28]: copy_my_l = my_l[:]

In [29]: my_l.append(4)

In [30]: my_l
Out[30]: [1, 2, 3, 4]

In [31]: copy_my_l
Out[31]: [1, 2, 3]
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321