2

I'm trying to change an item in a nested list. I thought this would be very straightforward. I have the following:

temp = [1, 2, 3, 4]
my_list = [temp for i in xrange(4)]
print "my_list = ", my_list

out: my_list =  [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]

So just a normal list of lists. I want to access one item:

print my_list[0][1]

out: 2

As expected. The problem comes when changing the item. I just want to change item in my_list[0][1], but I get the following:

my_list[0][1]= "A"
print my_list

out: [[1, 'A', 3, 4], [1, 'A', 3, 4], [1, 'A', 3, 4], [1, 'A', 3, 4]]

Why is it changing the four positions, instead of just one? How to avoid it?

Alejandro
  • 159
  • 1
  • 1
  • 9
  • @ajcr I just reopened the question because the suggested question was not exactly about this problem. I will be happy if you find a correct dup. – Mazdak Oct 27 '15 at 16:10
  • @Kasramvd: Hmm... I think http://stackoverflow.com/questions/240178/python-list-of-lists-changes-reflected-across-sublists-unexpectedly is the right duplicate for explaining the problem, but I agree that the solution isn't immediately obvious from those answers (so I guess the question could be left open). – Alex Riley Oct 27 '15 at 16:15

1 Answers1

2

Since lists are mutable objects when you repeat a list inside another one you just made a list of same objects (all of them point to one memory address),for getting rid of this problem You need to copy the nested lists in each iteration :

>>> temp = [1, 2, 3, 4]
>>> my_list = [temp[:] for i in xrange(4)]
>>> my_list[0][1]= "A"
>>> print my_list
[[1, 'A', 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]
>>> 
Chad S.
  • 6,252
  • 15
  • 25
Mazdak
  • 105,000
  • 18
  • 159
  • 188