Lists are a commonly used data structure in Python. When you use lists, there may be a situation where you need to copy or clone a list. There are several methods we can use to copy or clone a list.
copy()
If you need a shallow copy of a list, the built-in copy()
function can be used.
list.copy()
This function takes no parameters and returns a shallow copy of the list.
# delcaring a listoriginalList = [1, 2, 3, 4]# creating a shallow copy using functionshallowCopy = originalList.copy()print("Shallow copy: ", shallowCopy)# adding an element to the shallow copyshallowCopy.append(5)# printing the shallow copy after adding an elementprint("Shallow copy after appending an element: ", shallowCopy)# printing the original listprint("Original copy remains the same: ", originalList)
List slicing can be used to easily make a copy of a list. This method is called cloning. The original list will remain unchanged.
In this method, slicing is used to copy each element of the original list into the new list.
# delcaring a listoriginalList = [1, 2, 3, 4]# creating a clone using slicingcloneList = originalList[:]print("Clone of list: ", cloneList)# adding an element to clonecloneList.append(5)# printing the cloned list after adding an elementprint("Clone of list after appending element: ", cloneList)# printing the original list to show no changes took placeprint("Original copy remains the same: ", originalList)
for
loop and append()
In this method, a for
loop traverses through the elements of the original list and adds them one by one to the copy of the list, through append()
. The built-in append()
function takes a value as an argument and adds it to the end of a list.
list.append(val)
This creates a clone of the original list, so the original list is not changed.
# delcaring a list:originalList = [1, 2, 3, 4]# declaring an empty listcloneList = []# creating a clone using a loopfor i in originalList:cloneList.append(i)print("Clone of list: ", cloneList)# adding an element to the clonecloneList.append(5)# printing the cloned list after adding elementprint("Clone of list after appending element: ", cloneList)# printing the original list to show no changes took placeprint("Original copy remains the same: ", originalList)
When an assignment operator is used, a new list object will not be created. Instead, it will cause two variables to point to the same place in memory. So changing the copy will change the original.
# delcaring a listoriginalList = [1, 2, 3, 4]# creating a copy of the list using assignment operatornewList = originalListprint("Copy of list: ", newList)# adding an element to new listnewList.append(5)# printing the new copy list after adding elementprint("Copy of list after appending element: ", newList)# printing the original list to show it changed tooprint("Original copy is changed as well: ", originalList)
Free Resources