-2

I have a nested list A. I then let list B=list A. When I try to edit list B by changing some of its elements using B[1][2]=2, list A[1][2] gets changed too.

Why would this happen?

Mazdak
  • 105,000
  • 18
  • 159
  • 188
Relle
  • 1

4 Answers4

0

Because you are assigning a reference, so list B is actually pointing to list A. You would have to use copy of list. answered here:

python list by value not by reference

Community
  • 1
  • 1
hexerei software
  • 3,100
  • 2
  • 15
  • 19
0

Try this:

    A = [[1,2,3],[4,5,6],[1,2,3,4]]
    B = []
    for i in range(len(A)):
        c = list(A[i])
        B.append(c)

Then you will be able to change B without changing A.

jfish003
  • 1,232
  • 8
  • 12
-1

instead of:

listB = listA

try:

listB = listA[:]

And here's an excellent explanation for why this happens:

http://robertheaton.com/2014/02/09/pythons-pass-by-object-reference-as-explained-by-philip-k-dick/

Joe Young
  • 5,749
  • 3
  • 28
  • 27
-2

Edit explain whole though process…:

list = [[],[],[],[]]
a = 0
b = 3
list[a] = [1,2,3]
list[b] = list[a][:]

now list[b] is a copy and not the same list as list[a] and you cant edit them independently.

yamm
  • 1,523
  • 1
  • 15
  • 25
  • Apart from the fact that your solution will not work for nested lists, `list[a] = [1,2,3]` will yield `NameError: name 'a' is not defined` – SiHa Apr 01 '15 at 11:15
  • @SiHa why should this not work? you have list with nested lists. a represents one of them, lets say the first one a=0 and be an other one, maybe the b=3. then you set a if it is not set and copy a to b?? i actually tested it out. ofc this wont work if you just copy paste it. (edited the code so people who just copy paste will understand my though process^) – yamm Apr 01 '15 at 11:58
  • Your code is clearer now, but it still doesn't answer the OP's problem. You have shown how to copy a list from one element of a nested list to another element of the *same* list. The OP wanted to copy an entire nested list to another nested list. – SiHa Apr 01 '15 at 13:13
  • @SiHa uhh now i get what this list A and list B means ... a list called A and one called B. that totally confused me ;-) – yamm Apr 01 '15 at 13:40