0

I have a list a=[[1]] and b=[i for i in a]. Now i do b[0].append(2). When I print a and b, they are the same [[1, 2]] and [[1, 2]]. Looks like the list b[0] is referencing to the same one in a. Why does this happen?

a=[[1]]
b=[i for i in a]
b[0].append(2)
print a,b

Output: [[1, 2]] [[1, 2]]

Barmar
  • 741,623
  • 53
  • 500
  • 612
277roshan
  • 354
  • 1
  • 3
  • 13
  • Can you include the code you are using – DustinPianalto Dec 24 '15 at 01:58
  • what does 'print a is b' yeild. I believe your creation of b is just referencing that of a's elements, thus also updating them. There is a reason, bit I can't for the likes of me remember what it was, sorry. – user2589273 Dec 24 '15 at 02:03
  • So in order to make a completely new copy of list a, I would have to go in, get the elements, make new list and populate the new list? – 277roshan Dec 24 '15 at 02:05
  • a list don't contain the object themselves but a reference to that object, in your case when you copy the elements `a` of in `b` you copy say references, when you do the append python put that element in list reference by it, that is why you see the change in both – Copperfield Dec 24 '15 at 02:26

1 Answers1

3

a and b are different lists. But a[0] is the same list as b[0], because you didn't make a copy of it when you constructed b; the two lists contain references to the same sublists. You can make a copy of the sublist with:

b = [i[:] for i in a]

See How to clone or copy a list? for other ways to copy a list.

If you want to copy all levels at once, you can use copy.deepcopy()

import copy
b = copy.deepcopy(a)
Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612