How to Copy List Without Reference in Python 3
To copy an existing list to another one without reference, you can use the
second_list = first_list.copy()
See the following example:
first = [1, 2, 3, 4, 5, 6] second = first.copy()
In this example, we copied the first list to the second list using the
copy() function. The second list is a separate list, not a reference.
You can check the memory address of the first and the second list to make sure that they are not the same list:
first = [1, 2, 3, 4, 5, 6] second = first.copy() print(id(first)) print(id(second))
If you use the equal operator (=) instead of the
copy method, the second list becomes a reference to the first list. If you change one list, the other changes, too.