In this tutorial, we will see about Python List‘s copy method.Python List clear method is used to shallow copy the list.
Python List copy example
You can simply use copy method to shallow copy the list.It returns shallow copy of the list.
Let’s understand this with the help of simple example.
listOrig=l=[1,2,3,4] listCopy=listOrig.copy() listCopy.append(5) print("Original List:",listOrig) print("Copied list:",listCopy) print("List after clear:",l)
Copied list: [1, 2, 3, 4, 5]
As you can see change in copied list does not original list.
Let’s understand now, what is meant by shallow copy here.
listOrig=[['one','two'],['four','five']] listCopy=listOrig.copy() listCopy.append('three') print("Original List:",listOrig) print("Copied list:",listCopy)
Copied list: [[‘one’, ‘two’, ‘three’], [‘four’, ‘five’]]
As you can see here, change in inner list affected both the list.As when you use list’s copy method, it is actually shallow copy, so changes in inner list will impact both the list.
That’s all about Python List copy method.