Copy a list | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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

22nd Sep 2019, 7:44 PM
Coding Cat
Coding Cat - avatar
2 Answers
+ 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
23rd Sep 2019, 2:00 PM
Kshitij Singh
Kshitij Singh - avatar
+ 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.
22nd Sep 2019, 7:50 PM
HonFu
HonFu - avatar