Jun-30-2022, 04:35 PM
(This post was last modified: Jun-30-2022, 04:35 PM by deanhystad.)
list1 and list2 are the same list, not copies. As I said in my previous post if you want to copy a list you need to use copy().
list1.copy() makes a "shallow copy". It creates a new list, but the new list contains the same Python objects as list1. If list1 was a list of mutable objects, and you wanted the copied list to contain copies of the original list's contents, you need to do a "deep copy". Use the Python copy library functions to make a deep copy.
https://docs.python.org/3/library/copy.html
list1=["a","b","c"] list2=list1.copy() list1.remove("a") print("list1 = ",list1) print("list2 = ",list2)Variables in Python are really just names used to reference objects, not the objects themselves. You can see the python object using id(var) to see the actual python object referenced by a variable. In the code below, list2 = list1 results in both variables referencing the same list object. Printing the id's shows they are the same. list2=list1.copy() creates a new list object which is a copy of list1. When the id's are printed you can see they are different.
list1 = ["a", "b", "c"] list2 = list1 print("Same. list1", id(list1), "list2", id(list2)) list2.remove("a") print("list1 = ", list1) print("list2 = ", list2) list1 = ["a", "b", "c"] list2 = list1.copy() print("Copy. list1", id(list1), "list2", id(list2)) list2.remove("a") print("list1 = ", list1) print("list2 = ", list2)
Output:Same. list1 2106770607872 list2 2106770607872
list1 = ['b', 'c']
list2 = ['b', 'c']
Copy. list1 2106770607360 list2 2106770612480
list1 = ['a', 'b', 'c']
list2 = ['b', 'c']
You only have to worry about copies when the copying mutable objects. A mutable object is one that can be changed after it is created. Mutable Python types include: list, dictionary and set. Python strings (str) are immutable (cannot be changed). Making copies of immutable types makes no sense because the objects cannot be changed. Everyone can use the same object without fear that it will be modified somewhere else.list1.copy() makes a "shallow copy". It creates a new list, but the new list contains the same Python objects as list1. If list1 was a list of mutable objects, and you wanted the copied list to contain copies of the original list's contents, you need to do a "deep copy". Use the Python copy library functions to make a deep copy.
https://docs.python.org/3/library/copy.html