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.
1 2 3 4 5 6 7 8 9 |
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) |
Output:
Original List: [1, 2, 3, 4]
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.
1 2 3 4 5 6 7 |
listOrig=[['one','two'],['four','five']] listCopy=listOrig.copy() listCopy[0].append('three') print("Original List:",listOrig) print("Copied list:",listCopy) |
Output:
Original List: [[‘one’, ‘two’, ‘three’], [‘four’, ‘five’]]
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.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.