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?
-
@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.Kasravnd– Kasravnd10/27/2015 16:10:00Commented Oct 27, 2015 at 16:10
-
@Kasramvd: Hmm... I think stackoverflow.com/questions/240178/… 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– Alex Riley10/27/2015 16:15:33Commented Oct 27, 2015 at 16:15
1 Answer 1
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]]
>>>
-
This isn't caused by the mutability of lists, it's because everything in python is a reference.Chad S.– Chad S.10/27/2015 16:16:20Commented Oct 27, 2015 at 16:16
-
1@ChadS. but you don't see the same outcome with immutable objects, which are also referenced.jonrsharpe– jonrsharpe10/27/2015 16:17:04Commented Oct 27, 2015 at 16:17
-
By the way... so every time I slice a list, a copy is created instead of access to the same place in memory?Alejandro– Alejandro10/27/2015 16:18:13Commented Oct 27, 2015 at 16:18
-
@Alejandro It actually create a shallow copy of your lists read more docs.python.org/2/library/copy.htmlKasravnd– Kasravnd10/27/2015 16:21:13Commented Oct 27, 2015 at 16:21
-
1First time I post in the community, and feel overwhelmed with the fast responses, clarity and friendly vibe. Thanks for the answers. Very clear nowAlejandro– Alejandro10/27/2015 16:26:44Commented Oct 27, 2015 at 16:26