How to make a copy of a list?
When I use data_copy = data instead of data_copy = data[:], it seems after running the sorting both the original list and copy is getting affected. Can someone help me understand why we are using data[:] for making a copy of the list?
Hey Nirmal,
Thank you for the great question! The observation you've made is indeed very important.
In Python, when you write
data_copy = data
you are not making a true copy of the original list. Rather, you are pointing to it. This means that any changes you perform on the data_copy
list would affect the data
list as well.
One way to make a true copy of the original list is through slicing, just as Giles has done:
data_copy = data[:]
In this way, whatever changes you make on data_copy
won't be translated to the data
list. The concept of slicing is explained in Section 6: For Loops, Lecture: Lists.
A yet another way to make a true copy of the original list is by applying the copy()
method as follows:
data_copy = data.copy()
Again, any changes made on the data_copy
list won't affect the data
list.
Hope this helps!
Kind regards,
365 Hristina
Thank you sir