0

I'm having a problem writing the following code:

D = [
        [0,3,8,999,-4],
        [999,0,999,1,7],
        [999,4,0,999,999],
        [2,999,-5,0,999],
        [999,999,999,6,0]
    ]

def FloydWarshall (W):
    matrices = [W[:]]
    pred = [W[:]]

    print (matrices is pred)
    print (pred is matrices)
    print (pred is W)
    print (matrices is W)

    for i in range(0,len(pred[0])):
        for j in range(len(pred[0][i])):

            if pred[0][i][j] != 999 and pred[0][i][j] != 0:
                pred[0][i][j] = i +1
            else:
                pred[0][i][j] = False 

    return (matrices,pred)
FloydWarshall(D)

the values that are being returned are the exact same matrices, why is this? The print statement say that they are not pointers to the same spot in memory, correct?

3
  • The is keyword checks the id's of the two variables. The id's corresponds to the emplacements of the variables in memory (in CPython implementation). As said in the documentation: docs.python.org/3.3/library/functions.html#id Commented Apr 18, 2013 at 0:00
  • @segfolt: That's what OP wanted. a is b is True if they're the same object. Commented Apr 18, 2013 at 0:01
  • @Blender: Yes. That was just a precision because of the OP's last question. Commented Apr 18, 2013 at 0:23

1 Answer 1

5

You are only making a shallow copy of the nested lists, so mutating them will still affect both matrices. You might want to use copy.deepcopy

Sign up to request clarification or add additional context in comments.

1 Comment

Correct you are. Thank you!

Your Answer

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.