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?

asked Oct 27, 2015 at 16:02
2
  • @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. Commented 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). Commented Oct 27, 2015 at 16:15

1 Answer 1

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,67118 silver badges26 bronze badges
answered Oct 27, 2015 at 16:04
7
  • This isn't caused by the mutability of lists, it's because everything in python is a reference. Commented Oct 27, 2015 at 16:16
  • 1
    @ChadS. but you don't see the same outcome with immutable objects, which are also referenced. Commented 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? Commented Oct 27, 2015 at 16:18
  • @Alejandro It actually create a shallow copy of your lists read more docs.python.org/2/library/copy.html Commented Oct 27, 2015 at 16:21
  • 1
    First time I post in the community, and feel overwhelmed with the fast responses, clarity and friendly vibe. Thanks for the answers. Very clear now Commented Oct 27, 2015 at 16:26

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.