1

For args= ['', '0', 'P1', 'with', '10'] and students=[['1', '2', '3', 6]] it prints:

[[['1', '2', '3', 6]]]
[[['10', '2', '3', 6]]]

The expected output was :

[[['1', '2', '3', 6]]]
[[['1', '2', '3', 6]]]

But it somehow changes the backup_list any quick solutions?

backup_list.append(students[:])
print(backup_list)
students[int(args[1])][0] = args[4]
print(backup_list)

1 Answer 1

1

[:] make a shallow copy. You need a deep copy:

import copy

backup_list.append(copy.deepcopy(students))

Full program:

import  copy

backup_list = []
args= ['', '0', 'P1', 'with', '10']
students=[['1', '2', '3', 6]]
backup_list.append(copy.deepcopy(students))
print(backup_list)
students[int(args[1])][0] = args[4]    
print(backup_list)

Output:

[[['1', '2', '3', 6]]]
[[['1', '2', '3', 6]]]

The documentation explains the difference between shallow and deep copy:

A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.

A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

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

1 Comment

Thanks a lot it works, but can you explain more in deep why it does and why it doesn't with a shallow copy :3?

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.