Copy() method in python

In this article, we shall see the copy() method in python. Python has a built-in method called copy(). This method just copies the values alone instead of copying the address just like the assignment operator. It will be much easier to look at this with an example.

In order to understand what this method does, we have to first look at the problem with the assignment operator. Have a look at the following example.

a = [1, 2, 3, 4, 5]
b = a
b[0] = 0
print(b)
print(a)

The output of the above code is,

[0, 2, 3, 4, 5]
[0, 2, 3, 4, 5]

In the above example, I have a list ‘a’. I am assigning the list a to list b using the assignment operator. Now I am changing the first value of the list ‘b’ alone. But we can see that the value of the list ‘a’ is also changed if we change the value of the list ‘b’.

This is because using the assignment operator will copy the address and not just the value.

Now let us look at the same example using the copy() method.

copy() method

a = [1, 2, 3, 4, 5]
b = a.copy()
b[0] = 0
print(b)
print(a)

The output of the above code is,

[0, 2, 3, 4, 5]
[1, 2, 3, 4, 5]

We are doing the same thing here. But, instead of assigning with the assignment operator, we are using the copy() method to copy the values from one list to the other variable.

Altering or modifying the copied list(b) will only affect that list and the values in the original list are not affected. This is because the copy() method only will copy the values rather than copying the address.

Conclusion

If you are working with multiple lists, using the copy() method will be the sane choice. This way the original lists will not be affected and you can make as many changes possible to the original list.

Happy coding!