pythonpython-3.xlistlist-manipulation

How to create a new List in Python, such that manipulations to the new list does not affect the old one?


In the below code, I copied the contents of list a to contents of list prod. When I change prod list values, a list values are also getting changed.I also tried using prod=a[:]. I want the list a to be intact. Thanks in advance!l

a=[[1,2,3],[4,5,6],[7,8,9]]
b=[[1,2,3],[4,5,6],[7,8,9]]
prod=a.copy()
for i in range(3):
  sum=0
  for j in range(3):
    sum=0
    print("a= ",a[i][j])
    prod[i][j]=0
    print("a= ",a[i][j])
    for k in range(3):
      sum+=a[i][k]*b[k][j]
      print(a[i][k],b[k][j])
    prod[i][j]=sum  
    print("Sum=",sum,"A[i][k]=",a[i][k])
print(prod)

Solution

  • you need to deepcopy() it instead because it is nested lists..

    from copy import deepcopy
    
    a=[[1,2,3],[4,5,6],[7,8,9]]
    b=[[1,2,3],[4,5,6],[7,8,9]]
    prod= deepcopy(a)
    for i in range(3):
      sum=0
      for j in range(3):
        sum=0
        print("a= ",a[i][j])
        prod[i][j]=0
        print("a= ",a[i][j])
        for k in range(3):
          sum+=a[i][k]*b[k][j]
          print(a[i][k],b[k][j])
        prod[i][j]=sum  
        print("Sum=",sum,"A[i][k]=",a[i][k])
    print(prod)