In programming, we work a lot with "list" data structure.
Some might run into the issues when working with "list" in Python.
Often times we would like to copy a list to another variable to reuse.
So how do we do that in Python?
1.Wrong way:
old_list = ["Donald is a guy", "Sunshine", 3]
new_list = old_list
If we do this, it actually create a new variable "new_list" which points to the exact memory of old_list.
So when we change the value of old_list or new_list, both list will be changed.
old_list.append("Parapara")
new_list.append("akaka")
print(new_list)
print(old_list)
2.Correct way:
To copy a list, we need to make a slice that includes the entire original list by omitting the first index and the second index ([:]).
old_list = ["Donald is a guy", "Sunshine", 3]
new_list = old_list[:]
Then we append new item to the list
old_list.append("Parapara")
new_list.append("akaka")
print(new_list)
print(old_list)
Let's see the result:
That's it.
Happy coding!!!
Top comments (9)
You can also use
copy.copy()
andcopy.deepcopy()
.Yeah, I was thinking about that.
newlist = oldlist.copy()
copy
is a module wherecopy
is a function not a method.list objects have a .copy method.
Yeah but I meant my how my example works. 😅
Hi @cuongld2 !
Another way is to use the unpacking operator:
Don't forget you're performing a shallow copy though, if the list contains an object, you're sharing the same object between the original list and the copy:
as you can see now both lists, the original and the copy, have been modified, this is because the list contain a share object (the list
ls1
). If you want a deep copy you can use copy.deepcopy():There are limitations to what it can "deepcopy", the documentation contains further details.
Please don't use list unpacking for the sole purpose of creating a shallow copy of a list. Lists have a
.copy
method that should be used.I agree, my fault :) I was enumerating the various options :)
There are several other options, listed here, in which I find the
new_list = old_list.copy()
the most clear in intention and the most readable.