You can not copy one list to another list variable by simply assigning it with an equal sign (list_1 == list_2
).
In this case, list_2
is the only reference to list_1
, and when you make changes to list_1
, those changes automatically appear in list_2
.
The copy()
function in Python allows you to copy a list.
colors_list = ["Red", "Blue", "Green"]
copy_colors_list = colors_list.copy()
print(copy_colors_list)
['Red', 'Blue', 'Green']
In the above example, we copy the colors list using the copy()
function. In the output, you can see that the new copy colors list (copy_colors_list
) matches the original colors list (colors_list
).
You can also import a copy
module to copy the objects.
import copy as cp
colors_list = ["Red", "Blue", "Green"]
copy_colors_list = cp.copy(colors_list)
print(copy_colors_list)
['Red', 'Blue', 'Green']
In the above example, we imported the copy
module and copied the colors_list
to a copy_colors_list
.
You can also copy the list using Python built-in list()
function.
colors_list = ["Red", "Blue", "Green"]
copy_colors_list = list(colors_list)
print(copy_colors_list)
['Red', 'Blue', 'Green']
In the above example, we copy the colors list using the list()
function.
Using the id()
function, you can verify whether the list of copy objects is the same or different.
A numeric value is a return by the id()
function, which is memory address of the object.
colors_list = ["Red", "Blue", "Green"]
copy_colors_list_1 = colors_list
copy_colors_list_2 = list(colors_list)
print(id(colors_list), id(copy_colors_list_1))
print(id(colors_list), id(copy_colors_list_2))
4442206656 4442206656
4442206656 4442432960
As you can see in the output, assigned list objects have the same memory address, while copied list objects have different addresses.