+ 2
Copy a list
I want to copy a list to work only with that copy. But if I do so: list1 = list2, every change in list2 is also in list1. Is this something like reference? What is a short way to do this by value. To get two different lists? https://code.sololearn.com/c0fg7sBjI8H9/?ref=app
2 Respostas
+ 1
If the 2 list are named as list1 and list2 and you want to copy list1 to list2 then
list1=list(list2)
Is the answer to your questions
+ 6
If it's a simple list that doesn't contain other lists, you can just use either
list1 = list2[:]
or
list1 = list(list2)
Both create separate copies of the list.
If the list contain sub-lists, you need to make copies of these as well, which is uncomplicated if you know comprehensions:
list1 = [li[:] for li in list2]
For more complicated cases there is a module copy with deepcopy function in it.