Prevent the list that changes unexpected after assignment – Python ?

This tutorial guides you on how to prevent the list that changes unexpected after assignment using copy or clone in Python programming language.

List that changes unexpected after assignment

I have created a list called list1 and assigned that list to a new list called list2 as shown below. Then any modifications to the new list list2 also changes the old list list1.

```#create list
>>> list1 = [1,2,3]

#assignment
>>> list2 = list1

>>> list1
[1, 2, 3]

>>> list2
[1, 2, 3]

#modifications to new list
>>> list2.append(4)
>>> list2
[1, 2, 3, 4]

#impacted old list
>>> list1
[1, 2, 3, 4]```

Note, when you do list2 = list1, actually you don’t have two lists created, rather the assignment just copies the reference of the old list to the new list. Therefore, both lists list1 and list2 have the same reference so that you can treat them as same list after assignment.

Hence when you modify list2, list1 also changes.

Prevent the list unexpectedly changes after assignment

Now, lets see how to prevent the list unexpected changes after assignment using copy or clone.

Using list.copy()

It returns the shallow copy of the list. And it is equivalent to the following slice notation: “[:]”

```>>> list1 = [1,2,3]

#list.copy()
>>> list2 = list1.copy()
>>> list2
[1, 2, 3]

>>> list2.append(4)
>>> list2
list2
list2
[1, 2, 3, 4]

>>> list1
[1, 2, 3]```

Using slice notation

The slice notation is equivalent to list.copy() method.

For example,

```>>> list1 = [1, 2, 3]

#slice notation
>>> list3 = list1[:]

>>> list3
[1, 2, 3]

>>> list3.append(4)
>>> list3
[1, 2, 3, 4]

>>> list1
[1, 2, 3]```

Using list() function

Returns list whose elements are the same and in the same order as iterables in the list. Refer list function for more details.

```>>> list1 = [1,2,3]

#list() function
>>> list2 = list(list1)

>>> list2
[1, 2, 3]

>>> list2.append(4)
>>> list2
[1, 2, 3, 4]

>>> list1
[1, 2, 3]```

Using copy library

Basically, you can use shallow and deep copy operations using copy library and can change one copy without changing the other. This module provides two type of operations: shallow copy and deep copy.

Here is an example for shallow copy (copy.copy()).

```>>> list1 = [1,2,3]

>>> import copy
... list2 = copy.copy(list1)

>>> list2
[1,2,3]

>>> list2.append(4)
>>> list2
[1,2,3,4]

>>> list1
[1,2,3]```

The following is an example for deep copy (copy.deepcopy())

```>>> list1 = [1,2,3]

>>> import copy
... list2 = copy.deepcopy(list1)

>>> list2
[1,2,3]

>>> list2.append(4)
>>> list2
[1,2,3,4]

>>> list1
[1,2,3]```

That’s it. Basically, you had learnt how to prevent the list that changes unexpected after assignment using various approaches in Python programming language.

Hope it is helpful ðŸ™‚

Subscribe
Notify of