-2

Its bit confusing that I haven't gone any assignment of list a[] with list coy, still on output I get ,list a, same as ,list coy.I mean , how is that happening when I used coy=a[:].Thanks .

T=int(input())
for i in range(T):
    a=[]
    z=[]
    f=0
    count=0
    n,m=map(int,input().split())
    for i in range(n):
        a+=[list(map(int,input().split()))]
    coy=a[:]
    print(coy,'coy')#debug
    print(a,'a')#debug
    while(f==0):
        for i in range(n):
            for j in range(m):
                if i==0 and j==0:
                    coy[0][0]=max(a[i][j+1],a[i+1][j+1],a[i+1][j])
                elif i==0 and j==m-1:
                    coy[i][j]=max(a[i][j-1],a[i+1][j],a[i+1][j-1])
                elif i==n-1 and j==0:
                    coy[i][j]=max(a[i][j+1],a[i-1][j],a[i-1][j+1])
                elif i==n-1 and j==m-1:
                    coy[i][j]=max(a[i-1][j],a[i][j-1],a[i-1][j-1])
                elif j==0:
                    coy[i][j]=max(a[i][j+1],a[i-1][j],a[i+1][j],a[i-1][j+1],a[i+1][j+1],)
                elif j==m-1:
                    coy[i][j]=max(a[i][j-1],a[i-1][j],a[i-1][j-1],a[i+1][j],a[i+1][j-1])
                elif i==0:
                    coy[i][j]=max(a[i][j-1],a[i+1][j],a[i+1][j-1],a[i][j+1],a[i+1][j+1])
                elif i==n-1:
                    coy[i][j]=max(a[i][j-1],a[i-1][j-1],a[i-1][j],a[i-1][j+1],a[i][j+1])

                else:
                    coy[i][j]=max(a[i][j-1],a[i-1][j],a[i-1][j-1],a[i+1][j],a[i+1][j-1],a[i][j+1],a[i-1][j+1],a[i+1][j+1])
                    print('inside else','coy',coy,'a',a)#debug
        if(coy==a):
            print(coy,'coy')#debug
            print(a,'a')#debug

            count=0
            break

        for x in range(n):
            print('*')#debug
            z+=set(copy[x])
        print(z)
        if len(set(z))==1:
            f=1
        a=copy[:] 
        count+=1
        print('**********')#debug
    print(count)        

I have used some print statement for viewing the flow, and the value of ,list a, gets changed during assignment of list coy indices, which ideally shouldn't.

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
dodo
  • 89
  • 7

1 Answers1

0

Check the identity of both lists "a" and "coy" using id() function. Both the lists might be same, because both the objects are referred to the same data. Check out all other possibilities of copying one list to other here. How to clone or copy a list?

voidpro
  • 1,652
  • 13
  • 27
  • Both the lists "a' and "coy" have different ids. – dodo Jun 01 '17 at 10:49
  • Look at the answers on Shallow copy and Deep copy in Python lists. [List Copy1](https://stackoverflow.com/questions/8350750/python-copy-list-issue), [List Copy2](https://stackoverflow.com/questions/6993531/copy-list-in-python) – voidpro Jun 01 '17 at 11:25