Why in Python Does a Variable Copy Get Changed when You Change Its Source?

Problem scenario
You have a list in Python that you copy into another variable. You change the original list and the copied version changes. Why does the copied version get copied and what can you do to overcome this?

There is something called a "deep" copy and a "shallow" copy. This program will illustrate both the problem and the solution:

list_a = [3, 6, 7]
list_b = list_a
list_c = list_a[:]
print("list_b, a shallow copy, is above; list_a is below")
print("a different copy of list_a is below")

For more information, read the following links: StackOverflow.com and geeksforgeeks.com.

Leave a comment

Your email address will not be published. Required fields are marked *