/  Technology   /  List changes unexpectedly after assignment. Why is this and how can I prevent it?

List changes unexpectedly after assignment. Why is this and how can I prevent it?

List changes unexpectedly after assignment. Why is this and how can I prevent it?

 

We have considered a list named list_1 with the following elements and we assign this to a new list named list_2 using the “=” operator. 

Now after altering the data in list_1, if we try to print list_2, the change is reflected in it too.

Why is this happening?

It’s because, when we use the “=” operator we are not really making a copy, it is more like a list with two names, if one list is modified the other gets modified too.

What do we do if we want the copied list to be unaltered?

 

There are several ways to do this task. Let’s discuss a few in this article.

  1. Using list method copy()

This method returns a shallow copy of the main list. A shallow copy stores the references of objects to the original memory address. This reflects changes made to the new/copied object in the original object.

  1. Using slicing:

This method works similar to the list method copy(). We use slicing where the start_at and stop_ before values are null. This prints all the elements in the sequence. 

To learn more about slicing in sequences refer this article

https://www.i2tutorials.com/the-slice-notation/

  1. Using list():

The list() function returns all the items in the same order as in the argument passed to it.

  1. Using copy():

 

To implement this approach we import the copy library. Using this we can make both shallow and deep copies without changing the order.

Deep Copy: It stores copies of the object’s value. This doesn’t reflect changes made to the new/copied object in the original object.

The copy() function returns a shallow copy of the main list list_1.

The deepcopy() function returns a deep copy of the main list list_2.

Leave a comment