'How do I move values of one list to another list [duplicate]
I want to move the data from one list to another list to create a backup variable. I am currently using the code below but it seems to clear list1 for some reason too. If someone can explain the reasoning behind this and help me with a solution, I would be very grateful. I am new to python but I have some programming knowledge from Java.
list1 = list2
list2.clear()
Solution 1:[1]
The Python tutorial on W3Schools Copy Lists may help.
In Python you can copy list instances using my_list = my_other_list.copy(). This will create a copy of the list.
But why don't we just assign the list to a variable like my_list = my_other_list? That's because we would only point to the original list thus not creating a copy.
See also: List changes unexpectedly after assignment. Why is this and how can I prevent it?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | hc_dev |
